下面的示例代码在编译时给出了“使用未分配的局部变量‘resultCode’”:
string answer;
string resultCode;
try
{
resultCode = "a";
}
catch
{
resultCode = "b";
}
finally
{
answer = resultCode;
}
我本以为上面的 catch 块应该捕获所有异常,这样在进入 finally 块时 resultCode 就不可能被取消分配。任何人都可以透露一些信息吗?
谢谢。
编辑:谢谢大家。这个引用文档的答案似乎很好地回答了这个问题:https://stackoverflow.com/a/8597901/70140
为了显示:
string answer;
string resultCode;
try
{
// anything here could go wrong
}
catch
{
// anything here could go wrong
}
finally
{
answer = resultCode;
}
编译器目前无法假设或保证resultCode
曾经被赋予一个值。因此它会警告您可能会使用未分配的变量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)