【发布时间】:2014-03-20 23:53:12
【问题描述】:
IDE:Visual Studio 2010、C# .net 应用程序、winforms
我真的很惊讶这段代码 Code-1 运行良好
ErrorProvider ef = new ErrorProvider();
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == string.Empty)
{
ef.SetError(textBox1, "asdf");
}
else
{
ef.Clear();
}
}
但是这段代码代码2:
private void textBox1_TextChanged(object sender, EventArgs e)
{
ErrorProvider ef = new ErrorProvider(); //changes is here
if (textBox1.Text == string.Empty)
{
ef.SetError(textBox1, "asdf");
}
else
{
ef.Clear();
}
}
不工作,即它没有为我提供错误处理工具。谁能告诉我这两个代码之间有什么区别的确切原因。以及为什么第二个代码不能正常工作..
【问题讨论】:
-
看起来 ErrorProvider 在另一个地方被评估。你创建了一个局部变量,它隐藏了一个潜在的成员 ef 并在你的方法离开后丢失。