C# - 无法从事件处理程序访问全局变量

PDo*_*ria 2 c# variables null global reference

我有一个带有全局变量的Windows窗体应用程序 - 一个名为的字符串testPath.

此字符串用于保存路径 - 默认情况下C:\temp\.当用户单击按钮时,将创建此目录(如果它尚不存在).

如果用户想要更改路径的值,还有一个文本框控件.

在按钮的事件处理程序中,我尝试访问testPath并获得空引用.

我没有改变testPath任何地方的值,除非我将它传递给文本框Control和从文本框Control传递.

我究竟做错了什么?全局变量如何在一秒内有内容,然后在之后它指向空引用?

这是完整的代码:

public string testPath = @"C:\temp\";

public MainForm()
{
     //Windows Designer call
     InitializeComponent();

     //Show the testPath in the textBox (using Invokes)
     this.textBox1.Invoke(new MethodInvoker(delegate { this.textBox1.Text = testPath; } ));

     //here, testPath contains 'C:\temp\'
}

//Button "Click" handler
private void Button1Click(object sender, EventArgs e)
{
     //here, testPath contains a null reference!

     //If the user changed testPath in the textBox, we need to save it again
     this.textBox1.Invoke(new MethodInvoker(delegate { testPath = this.textBox1.Text; } ));

     //Create the path
     if(!Directory.Exists(testPath)) //If it does not exist already
     {
         Directory.CreateDirectory(testPath); 
     }

     //...Do something else

}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 8

我建议把它变成一个常数:

const string testPath = @"C:\temp\";
Run Code Online (Sandbox Code Playgroud)

这将导致任何尝试将值设置为标记为编译器错误.使用该值将无需更改即可使用.


编辑以回应评论:

由于您想要更改该值,我建议将其重新设置为属性:

private string _testPath = @"C:\temp\";
private string testPath 
{ 
    get { return _testPath; }
    set
    {
        _testPath = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在该行上设置断点_testPath = value;,并在调试器中查看确切设置的内容null.一旦纠正,我会建议修复命名以匹配标准的.NET命名约定.

  • @Yatrix是的 - 某个地方的其他东西正在设置它.通过使它成为`const`,原始海报将能够准确地看到导致它被设置为null的原因,因为它是编译器错误. (2认同)