C# - 使用已定义的未分配局部变量
C# - Use of unassigned local variable that has already been defined
我已经在我的 for 循环之外声明了布尔变量“已激活”,我正在 for 循环内更改它的值,当我试图在我的循环之外使用它时 return语句,说的是未赋值。有什么想法吗?
private bool validityCheck()
{
char[] invalidCharacters = { '*', '\'', '.', ';', ':', ',' };
bool activated;
for (int i = 0; i < invalidCharacters.Length; i++)
{
activated = false;
if (textBox1.Text.Contains(invalidCharacters[i]))
{
ErrorHandling(45, "Fields contain invalid characters", false);
textBox1.BackColor = Color.Red;
activated = true;
}
if (textBox2.Text.Contains(invalidCharacters[i]))
{
if (activated)
ErrorHandling(45, "Fields contain invalid characters", false);
textBox2.BackColor = Color.Red;
}
}
return activated;
}
如果我简单地删除 for
:
,我绝对希望发生这种情况
private bool validityCheck()
{
bool activated;
return activated;
}
但是由于循环总是至少有一次迭代,我希望编译器足够聪明,能够弄清楚这一点,并理解 actived
在代码离开循环之前被赋值。 (我听说过可能与此相关的术语“明确赋值”,但 C# 规范对我来说太难解析了)
Microsoft 关于错误的文档 CS0165 Use of unassigned local variable 'activated'
指出
This error is generated when the compiler encounters a construct that
might result in the use of an unassigned variable, even if your
particular code does not. This avoids the necessity of overly complex
rules for definite assignment.
错误的存在是为了减轻编译器在循环中确定是否已分配值的任务(当它在 if
语句的主体内时会发生一些事情。)
避免错误的最简单方法是在循环之前为变量赋值。
我已经在我的 for 循环之外声明了布尔变量“已激活”,我正在 for 循环内更改它的值,当我试图在我的循环之外使用它时 return语句,说的是未赋值。有什么想法吗?
private bool validityCheck()
{
char[] invalidCharacters = { '*', '\'', '.', ';', ':', ',' };
bool activated;
for (int i = 0; i < invalidCharacters.Length; i++)
{
activated = false;
if (textBox1.Text.Contains(invalidCharacters[i]))
{
ErrorHandling(45, "Fields contain invalid characters", false);
textBox1.BackColor = Color.Red;
activated = true;
}
if (textBox2.Text.Contains(invalidCharacters[i]))
{
if (activated)
ErrorHandling(45, "Fields contain invalid characters", false);
textBox2.BackColor = Color.Red;
}
}
return activated;
}
如果我简单地删除 for
:
private bool validityCheck()
{
bool activated;
return activated;
}
但是由于循环总是至少有一次迭代,我希望编译器足够聪明,能够弄清楚这一点,并理解 actived
在代码离开循环之前被赋值。 (我听说过可能与此相关的术语“明确赋值”,但 C# 规范对我来说太难解析了)
Microsoft 关于错误的文档 CS0165 Use of unassigned local variable 'activated'
指出
This error is generated when the compiler encounters a construct that might result in the use of an unassigned variable, even if your particular code does not. This avoids the necessity of overly complex rules for definite assignment.
错误的存在是为了减轻编译器在循环中确定是否已分配值的任务(当它在 if
语句的主体内时会发生一些事情。)
避免错误的最简单方法是在循环之前为变量赋值。