gpt4 book ai didi

c# - 在 C# 中,为什么在 finally block 的开头没有明确分配变量?

转载 作者:太空狗 更新时间:2023-10-30 00:40:19 24 4
gpt4 key购买 nike

我不明白为什么下面的代码会产生错误。通常我可以从语言规范中弄明白,但在这种情况下我不理解语言规范。

顺便说一下,这不会导致我的代码出现问题,我只是想了解这门语言。

例子:

bool success;
try
{
success = true;
}
catch
{
success = false;
}
finally
{
Console.WriteLine(success); // ERROR: Local variable 'success' might not be initialized before accessing
}

此行为似乎适用于所有 C# 版本,但下面的引用来自 C# Language Specification 5.0 .

第 5.3.3.14 节 Try-finally 语句

The definite assignment state of v at the beginning of finally-block is the same as the definite assignment state of v at the beginning of stmt.

这里“stmt 的开始”是指整个 try-finally 语句的开始,即在 try 之前。

5.3.3.15 节 Try-catch-finally 语句

The following example demonstrates how the different blocks of a try statement (§8.10) affect definite assignment.

static void F() {
int i, j;
try {
goto LABEL;
// neither i nor j definitely assigned
i = 1;
// i definitely assigned
}
catch {
// neither i nor j definitely assigned
i = 3;
// i definitely assigned
}
finally {
// neither i nor j definitely assigned
j = 5;
// j definitely assigned
}
// i and j definitely assigned
LABEL:;
// j definitely assigned
}

谁能解释为什么 success(在我的示例中)或 i(在语言规范示例中)没有在 finally block 的开头明确分配?

最佳答案

原因很简单 - 无法保证 trycatch block 中的代码会在 finally block 之前执行。

ThreadAbort 异常可能发生在 try block 内,但在赋值执行之前。

运行时代码在抛出异常之后但在 catch block 中的代码执行之前执行(搜索异常处理在 .Net 中的工作方式或“结构化异常处理”)。

因此,在执行 finally block 之前,try 和 catch block 中的代码可能永远不会执行。

关于c# - 在 C# 中,为什么在 finally block 的开头没有明确分配变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28755949/

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