【发布时间】: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;
-
我明白了。这是一个逻辑错误。谢谢你:)