gpt4 book ai didi

c# - 在 try-catch-finally 中使用未分配的局部变量

转载 作者:太空狗 更新时间:2023-10-30 01:14:39 25 4
gpt4 key购买 nike

下面的示例代码在编译时给出了“使用未分配的局部变量‘resultCode’”:

    string answer;
string resultCode;

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

我原以为上面的 catch block 应该捕获所有异常,因此在进入 finally block 时 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 曾被赋值。因此它会警告您可能会使用未分配的变量。

关于c# - 在 try-catch-finally 中使用未分配的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42287545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com