C# 规范(5.3.3.14)的一些背景:
对于以下形式的 try 语句 stmt:
尝试 try-block finally finally-block
(...)
finally-block开头的v的确定赋值状态与stmt开头的v的确定赋值状态相同。
编辑 Try-Catch-Finally(5.3.3.15):
对 try-catch-finally 语句 (...) 进行明确的赋值分析,就像该语句是包含 try-catch 语句的 try-finally 语句一样
以下示例演示了 try 语句(第 8.10 节)的不同块如何影响明确赋值。
class A
{
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
}
}
我只是想到了一个更好地说明问题的例子:
int i;
try
{
i = int.Parse("a");
}
catch
{
i = int.Parse("b");
}
finally
{
Console.Write(i);
}