2017-02-17 113 views
4
編譯時

示例代碼下面給出了一個「未分配的局部變量‘resultCode爲’使用」異常,並且在finally代碼塊輸入時resultCode不可能被分配。任何人都可以點亮一下嗎? 謝謝。使用未分配的局部變量的使用try-catch-finally程序

編輯:謝謝大家。這個答案它引述的文件似乎回答得好:https://stackoverflow.com/a/8597901/70140

+2

如果'resultCode =「a」;'會引發異常?我意識到它不會,但編譯器不知道這一點。 – DavidG

+0

發現一些愚蠢:http://stackoverflow.com/questions/8597757/use-of-unassigned-local-variable-but-always-falls-into-assignment http://stackoverflow.com/questions/20521993/use -of-unassigned-local-variable-on-finally-block –

回答

2

爲了說明:在這一點上resultCode是有史以來分配一個值

string answer; 
string resultCode; 

try 
{ 
    // anything here could go wrong 
} 
catch 
{ 
    // anything here could go wrong 
} 
finally 
{ 
    answer = resultCode; 
} 

編譯器不能承擔或擔保。所以它警告你可能會使用未分配的變量。

+1

+1但我認爲值得補充的是,如果'finally'塊或所有'try'和'catch'塊都明確賦值,那麼它它完全是在整個構造之後定義的。 –

0

編譯器無法保證trycatch塊內的任何代碼將實際運行而不會發生異常。理論上,當您嘗試使用它時,其值爲resultCode未分配。

+1

downvote?祈禱告訴你爲什麼...... – DavidG

0

Visual Studio不知道你正在給'resultCode'賦值。你需要事先給它一個價值。示例代碼在底部。

這作爲一個層次結構。 Visual Studio在try/catch中看不到'resultCode'的定義。

string answer = ""; 
string resultCode = ""; 

try 
{ 
    resultCode = "a"; 
} 
catch 
{ 
    resultCode = "b"; 
} 
finally 
{ 
    answer = resultCode; 
} 
+0

爲什麼'「」是正確的值? –

+0

這不是,但不管發生了什麼,它都會在try/catch中定義。編譯器只是不知道。 –

1

添加一些解釋,例如,在下面的代碼中,變量n在try塊內被初始化。試圖在Write(n)語句的try塊外使用此變量將產生編譯器錯誤。

int n; 
try 
{ 
    int a = 0; // maybe a throw will happen here and the variable n will not initialized 
    // Do not initialize this variable here. 
    n = 123; 
} 
catch 
{ 
} 
// Error: Use of unassigned local variable 'n'. 
Console.Write(n); 

正如意見建議,如果你在Try,並在Catch這樣也分配,ADN試塊

string answer; 
string resultCode; 

try 
{ 
    resultCode = "a"; 
} 
catch 
{ 
    resultCode = "b"; 
} 
finally 
{ 
    // answer = resultCode; 
} 
answer = resultCode; 

它將編譯後分配。

相關問題