C# winforms 中的静态类变量作用域问题 - 为什么这段代码不起作用?
我的 WinForms 应用程序中有两种不同的表单(例如 MainForm 和 Form2)。它们都要求通过“getInstance”静态方法访问 MyDataSet。问题是在 MainForm 获得实例之后,当 Form2 需要获取实例时,静态“myDataSet”变量为 null,而我期望已经设置?有什么想法吗?
public class MyDataSet
{
public static MyDataSet myDataSet;
// This was null 2nd call to getInstance
private DataSet myData = new DataSet();
public static MyDataSet GetInstance()
{
if (myDataSet == null)
{
return new MyDataSet();
}
else
{
return myDataSet;
}
}
所以看起来静态“myDataSet”变量在只有一次实例的情况下不起作用?
I've got two different forms in my WinForms app (MainForm and Form2 say). They both ask for an access of MyDataSet, via a "getInstance" static method. The issue is after MainForm has got an instance, when Form2 needs to get an instance the static "myDataSet" variable is null, whereas I expect to have been already set? Any ideas?
public class MyDataSet
{
public static MyDataSet myDataSet;
// This was null 2nd call to getInstance
private DataSet myData = new DataSet();
public static MyDataSet GetInstance()
{
if (myDataSet == null)
{
return new MyDataSet();
}
else
{
return myDataSet;
}
}
So it almost seems the static "myDataSet" variable isn't working in terms of only having once instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您忘记将新创建的实例分配给 myDataset
you forgot to assign the newly create instance to myDataset
您没有设置
myDataSet
这是正确的代码:
You didn't set
myDataSet
This is the correct code:
请查看 Jon Skeet 发表的这篇文章。正如其他人所说,您没有设置变量,但您可能还想实现更健壮的模式,或者可能摆脱单例。事实上,您最终可能会创建 MyDataSet 的多个实例。
如果您需要单例,我会选择第四或第五版本。
Take a look at this article from Jon Skeet. As others have said you are not setting the variable but you might also want to implement a more robust pattern, or perhaps get rid of the singleton. As it is you could end up multiple instances being created of MyDataSet.
I would go with the fourth or fifth version, if you need a singleton.