【问题标题】:Scope of variables error变量范围错误
【发布时间】:2017-11-19 17:01:43
【问题描述】:

我对 C# 编程非常陌生。

我在我的程序中发现了这个奇怪的范围错误,我的程序无法运行。它在下面(在 lbl[tx].BackColor = Color.DarkViolet;)说“使用未分配的局部变量”。但是我已经在我的方法中声明了变量 tx 。

如何解决这个问题?非常感谢任何帮助。

        async void ShellSort()
    {
        int n = num.Length;
        int gap = n / 2;
        int temp;
        int tx; /// Already declared tx here

        while (gap > 0)
        {
            for (int i = 0; i + gap < n; i++)
            {

                int j = i + gap;
                temp = int.Parse(lbl[j].Text);


                while (j - gap >= 0 && temp < int.Parse(lbl[j - gap].Text))
                {
                    lbl[j-gap].BackColor = Color.Blue;
                    lbl[j].BackColor = Color.Blue;

                    await Task.Delay(time1);
                    lbl[j].Text = lbl[j - gap].Text;
                    tx = j;
                    j = j - gap; 
                }
                lbl[j].Text = temp.ToString();
                lbl[j].BackColor = Color.DarkViolet;
                lbl[tx].BackColor = Color.DarkViolet; /// When I used
                /// it here it wont work.
            }

            gap = gap / 2;
        }
    }

【问题讨论】:

  • 旁注:async void 是一个众所周知的坏主意。使用async Task,这样可以通过调用代码来等待、观察等操作。
  • 您声明了它但从未分配它,因为消息状态:“使用 未分配 局部变量”。例如,如果您不进入 while 循环,则永远不会为 tx 分配值。
  • 你必须初始化 tx
  • 内部循环不走怎么办?如果不运行您的程序,编译器无法发现这种情况。所以它告诉你在内部循环之外使用变量 tx 是错误的。声明时只需将变量 tx 设置为零 int tx = 0;
  • 我明白了。这是一个逻辑错误。谢谢你:)

标签: c# variables scope


【解决方案1】:

声明变量,但不向它分配任何东西:

int tx;

可能在循环中分配给它:

while (j - gap >= 0 && temp < int.Parse(lbl[j - gap].Text))
{
    //...
    tx = j;
    //...
}
// use tx here

但是,如果循环条件以false 开头会发生什么?如果从未进入循环,则不会分配任何值。编译器不能冒险。尽管您可能为其分配了一个值,但编译器需要确保您确实为其分配了一个值。

您可以通过简单地为其分配一个默认值来做到这一点:

int tx = 0;

当涉及到属性等等时,整数默认为0。所以也可以对局部变量做同样的事情。

【讨论】:

    【解决方案2】:

    如果您的 while 的主体永远不会被执行,tx 将被取消分配。编译器只是告诉您这种情况需要初始值。

    所以不是

    int tx;
    

    int tx = 0; // or what is the correct value for you
    

    【讨论】:

      猜你喜欢
      • 2016-04-02
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多