C# 有人能告诉我以下错误提供程序代码之间的区别吗?

C# 有人能告诉我以下错误提供程序代码之间的区别吗?,c#,.net,winforms,C#,.net,Winforms,IDE:VisualStudio2010,C#.net应用程序,winforms 我真的很惊讶这个代码code-1工作得很好 ErrorProvider ef = new ErrorProvider(); private void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text == string.Empty) { ef.Set

IDE:VisualStudio2010,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();
        }
    }

不工作,即不提供错误处理功能。有人能告诉我这两种代码之间的区别的确切原因吗。以及为什么第二个代码不能正常工作。

code1中,您在事件处理程序的范围之外创建
ef
对象,这样处理事件后
ef
对象仍然存在,其中,与code2中一样,
ef
对象在处理事件后会被销毁。

看起来像是在另一个地方对ErrorProvider进行了评估。您创建了一个局部变量,它隐藏了一个潜在的成员ef,并在方法离开后丢失。因此,如果我将此代码移动到函数中,那么此代码是否有效。。?我从一个text_changed事件private void HandleErrorProvider(){ErrorProvider ef=new ErrorProvider();if(textBox1.text==string.Empty){ef.SetError(textBox1,“asdf”);}else{ef.Clear();}}}@yogeshkmrsoni为什么不希望errorProvider成为表单的一个字段?这是“通常”的方式!请看msdn:yogeshkmrsoni,我建议你仔细阅读物体的寿命以及它们何时被摧毁。我想这会消除你的困惑。@Raphaël Althaus没有具体的原因,只是想知道为什么它不起作用。但GregoryHouseMD已经澄清了我的疑问。谢谢