为什么我的变量仍然“未初始化”?

时间:2012-05-24 07:02:47

标签: c#

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;”。我想申报,但是按时完成作业!

6 个答案:

答案 0 :(得分:2)

您必须将第一行更改为string foo = null或根据需要进行初始化。就编译器而言,在try块中初始化foo之前可能存在异常,并且catch也可能不会发生。

答案 1 :(得分:2)

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

  

对于表单的try语句stmt:

     

尝试try-block finally finally-block

     

(...)

     

最后一个块开头的v的明确赋值状态   与开头的v的明确赋值状态相同   语句。

编辑Try-Catch-Finally(5.3.3.15):

  

try-catch-finally语句的明确赋值分析(...)   就像声明是一个包含a的try-finally语句一样   try-catch语句

     

以下示例演示了如何尝试不同的块   声明(第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);
}

答案 2 :(得分:2)

我认为问题可能是两者 trycatch抛出异常的情况。在这种情况下,仍应达到finally,但未初始化foo。因为在这种情况下,将无法访问其余代码(catch块中抛出的异常将我们带出finally之后的方法,这不会产生问题finally之后的代码。只有在trycatch块运行时才能访问该代码。

由于始终存在foo的每个赋值都抛出异常的情况,并且因为在这种情况下finally块总是会运行,所以始终存在{{1}的可能性未被初始化。

据我所知,解决这个问题的唯一方法是为foo提供初始化值。

答案 3 :(得分:0)

在课程级别声明你的string foo它将解决问题

编辑:

string foo = "default";
try
{
    foo = "test"; 
}
catch (Exception) 
{
    foo = null;
}
finally
{
    Console.WriteLine(foo); 
}

答案 4 :(得分:-2)

string foo = string.Empty;

答案 5 :(得分:-2)

试试这个:

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