2017-02-17 117 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; 

它将编译后分配。

相关问题