为什么我的变量仍然是

为什么我的变量仍然是

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(捕获路由)-但这是我可以获得的最佳隔离。
但是我听到一阵好消息,告诉我“危险,危险-可能尚未初始化”。
怎么会?

编辑:
请不要建议“仅在'declaration'处放置一个string foo = string.Empty;”。我想声明一下,但要准时完成作业!

最佳答案

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



编辑Try-Catch-Finally(5.3.3.15):


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/

10-12 12:42