2013-07-22 37 views
3

考慮以下代碼:爲什麼我們不需要在「使用」範圍之外返回一個值?

public int DownloadSoundFile() 
{ 
    using (var x= new X()) 
    { 
     return x.Value; 
    } 
} 

和驗證碼:

public int DownloadSoundFile() 
{ 
    if (x!=null) 
    { 
     return x.Value; 
    } 
} 

第一個代碼不給我們任何編譯時錯誤,但在第二個代碼中,我們得到這個錯誤:

not all code paths return a value

這意味着我們應該返回if範圍以外的值。

爲什麼我們必須返回if作用域之外的值,但不需要返回using作用域之外的值?

+3

在這種情況下,使用(...){return ...; }'和'{return ...; }'。 – Leri

回答

21

why we should return value out of the if scope but don't need return value out of the using Scope?

由於if範圍可能不執行(如果該條件不成立),而using範圍的主體被保證始終執行(它要麼返回結果或拋出異常,其是用於在可接受的編譯器)。對於if範圍,如果條件不滿足且編譯器拒絕該方法,則您的方法未定義。

所以,你應該決定返回什麼價值,如果你寫的條件不滿足:

public int DownloadSoundFile() 
{ 
    if (x != null) 
    { 
     return x.Value; 
    } 

    // at this stage you should return some default value 
    return 0; 
} 
+0

但是我們應該使用 –

+3

當你處理'IDisposable'實例時,你應該使用'using'。它將確保始終調用Dispose方法。 –

+0

@ShahroozJefriㇱhttp://stackoverflow.com/questions/75401/uses-of-using-in-c-sharp – Jodrell

8

so we should return value out of the if scope.

號,您應該返回從int method()的值。它與if()using()無關。

public int DownloadSoundFile() 
{ 
    if (x!=null) 
    { 
     return x.Value; 
    } 
    // and now?? no return value for the method 
    // this is a 'code path that does not return a value' 
} 
1
public int DownloadSoundFile() 
{ 
    if (x!=null) 
    { 
     return x.Value; 
    } 
} 

在此代碼,如果X是什麼null!在這種情況下,函數將如何返回值。所以正確的代碼是。

public int DownloadSoundFile() 
{ 
    if (x!=null) 
    { 
     return x.Value; 
    } 
    else 
    { 
     // your return statement; 
    } 
} 

您還可以使用下面的代碼。

return x != null ? x.value : *something else* 

使用未使用返回的東西,它主要是用來使代碼不會因爲異常的突破。主要是使用語句創建數據庫連接。因爲這樣可以確保連接異常被抑制,並且一旦超出範圍,連接就會關閉。一般情況下,從IDisposable繼承的對象將在using語句中使用,以便調用dispose()方法。

+1

-1這不是三元運算符在c#中的工作方式 – Leri

+0

如果我們以這種方式使用?:運算符,會出現什麼問題? http://msdn.microsoft.com/en-US/library/ty67wk28(v=VS.80).aspx。 return語句也是表達式,所以我們可以在裏面使用它們:: – Narendra

+0

從[docs](http://msdn.microsoft.com/en-us/library/ty67wk28(v = vs.80).aspx):'The條件運算符(?:)根據布爾表達式的值返回兩個值中的一個。「這意味着'條件? first_statement:second_statement'無效。 – Leri

0

using是下面的代碼一個別名:

IDisposable x = null; 
try 
{ 
    x= new X(); 
    //inside the using 
    return x.Value; 
} 
finally 
{ 
    if(x != null) 
     x.Dispose(); 
} 

所以,你可以發現,每一個路徑返回一個值;事實上,只有一條路徑(或者可能是一條路徑)。

相關問題