【问题标题】:C# Use of Unassigned local variable - out statementC#使用未赋值的局部变量——out语句
【发布时间】:2012-08-20 12:58:11
【问题描述】:

我一直在寻找这个问题,但我不知道(也没有找到)如何解决它。这里有谁知道如何解决这个问题?我正在使用 EMGU,但问题在于 c# 编码(我对 C# 相当陌生) - 我认为这与 out 语句有关,因为我没有经常使用它们:

Image<Gray, Byte> first_image;

if (start_at_frame_1 == true)
{
    Perform_custom_routine(imput_frame, out first_image);
}
else
{
     Perform_custom_routine(imput_frame, out second_image);
}

Comparison(first_image);

【问题讨论】:

  • 如果start_at_frame_1 为假,则尚未为first_image 分配对Comparison() 的调用的值。这就是你被警告的。如何修复它取决于您想要的行为。此外,== true 是一个冗余测试 - 你可以只使用 if(start_at_frame_1)

标签: c# out


【解决方案1】:

你必须给变量默认值:

Image<Gray, Byte> first_image = null;

否则,如果您将 second_image 作为 out 参数传递,您可能不会分配任何内容。

【讨论】:

    【解决方案2】:

    编译器警告您,您将在调用Comparison 时使用未分配的变量。如果start_at_frame_1false,你的变量first_image 永远不会被设置。

    您可以通过在初始化或 else 块中设置 first_image = null 来解决此问题。

    【讨论】:

      【解决方案3】:

      你有 3 种选择

      Image<Gray, Byte> first_image = default(Image<Gray, Byte>);
      

      Image<Gray, Byte> first_image = null;
      

      Image<Gray, Byte> first_image = new Image<Gray, Byte>();
      

      别忘了也用second_image 来做这件事。

      【讨论】:

      • @AdamHouldsworth 不,在 else 块中,out 参数是 second_image 而不是 first_image,因此存在不会重新分配的情况。
      • @Hinek True,一开始并没有发现。但是,在Perform_custom_routine(imput_frame, out first_image); 被调用的情况下,first_image 保证会被重新分配,因此在这种情况下分配new Image 将毫无意义。
      • 这些是几个选项中的三个,而不是仅有的三个选项。您还可以确保在 else 块中分配它,或者将所有对 first_image 的调用移到 if 块中,仅举几例。
      【解决方案4】:

      或者您可以将其作为 Perform_custom_routine 的返回参数。

      Image<Gray, Byte> first_image;  
      
      if (start_at_frame_1 == true)  
      {  
          first_image = Perform_custom_routine(imput_frame, out first_image);  
      }  
      else  
      {  
           first_image = Perform_custom_routine(imput_frame, out second_image);  
      }  
      

      【讨论】:

        【解决方案5】:

        如果你使用'out'关键字,你必须在传递变量之前给它一个值。

        如果你使用'ref'关键字,你必须在返回之前在你传递给它的方法中给变量一个值。

        【讨论】:

        • 调用函数时 out 变量不应该有值...除非我完全错误地阅读了您的文本。
        • 我不知道为什么在这里投反对票 - 一个 ref 变量必须在它作为参数传递之前分配,而 Out 不需要!
        猜你喜欢
        • 1970-01-01
        • 2014-04-22
        • 2011-05-05
        • 1970-01-01
        • 1970-01-01
        • 2013-02-28
        • 2022-11-14
        相关资源
        最近更新 更多