【发布时间】:2012-02-01 15:52:37
【问题描述】:
我只是尝试在 WinForms 中实现单例模式,这样只有一个表单实例留在应用程序生命中,但我遇到了困难
如果单例的实例存在,我想抛出异常并同时返回相同的实例引用。
SingletonForm.cs
public class SingletonForm : BaseFormcs
{
private static SingletonForm _instance;
//To stop new keyword from instantiation
private SingletonForm()
{ }
public static SingletonForm GetInstance()
{
if (_instance == null)
return _instance = new SingletonForm();
else
{
throw new Exception("Form already exists"); // execution returns from here
return _instance; // Warning : Unreachable code detected
//I also want to return instance reference.
}
}
}
【问题讨论】:
-
在这种情况下为什么要抛出异常?这对我来说没有多大意义。
-
请注意,您的单例实现不是线程安全的。
-
这个问题几乎不值得回答,因为这似乎是一种非常糟糕的做法,但您可以使用 out 参数。公共静态 SingletonForm GetInstance(out Exception ex) { }
-
@BrokenGlass:我只是想有时我可能需要同时使用两者,这就是我问的原因,我只是在玩这个单例样本......