gpt4 book ai didi

c# - 为什么我的变量仍然是 "uninitialized"?

转载 作者:太空狗 更新时间:2023-10-29 21:55:04 26 4
gpt4 key购买 nike

string foo;
try
{
foo = "test"; // yeah, i know ...
}
catch // yeah, i know this one too :)
{
foo = null;
}
finally
{
Console.WriteLine(foo); // argh ... @#!
}
Console.WriteLine(foo); // but nothing to complain about here

除了它不是 BP(捕获路由)——但这是我能得到的最好的隔离。
但是我得到了很好的波浪告诉我“危险,危险 - 可能未初始化”。怎么来的?

编辑:
请不要建议“在‘声明’处简单地放置一个 string foo = string.Empty;”。我想申报,但按时完成作业即可!

最佳答案

C# 规范 (5.3.3.14) 的一些背景:

For a try statement stmt of the form:

try try-block finally finally-block

(...)

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.

编辑 Try-Catch-Finally(5.3.3.15):

Definite assignment analysis for a try-catch-finally statement (...) is done as if the statement were a try-finally statement enclosing a try-catch statement

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

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);
}

关于c# - 为什么我的变量仍然是 "uninitialized"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10732670/

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