假设我们有这些类:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Controller controller;
private uControl uc; //user control
public static Singleton Instance
{
get { return Singleton.instance; }
}
public Controller GetController
{
get
{
if (this.controller == null)
{
this.controller = new Controller();
}
return this.controller;
}
}
public uControl UC
{
get
{
if (this.uc == null)
{
this.uc = new uControl();
}
return this.uc;
}
}
}
public uControl : UserControl
{
Controller controller = Singleton.Instance.GetController;
// Do some work with controller class here ...
}
public Form1 : Form
{
public Form1()
{
this.Controls.Add(Singleton.Instance.UC);
}
}
public Form2 : Form
{
public Form2()
{
this.Controls.Add(Singleton.Instance.UC);
}
}
是否可以通过 Singleton 将用户控件 uControl 添加到两种不同的形式中,并期望它们在访问同一个控制器类时正常工作?
当我尝试这个时,只有首先实例化的表单才能正确显示 uControl。另一个表单将获得 uControll OK,但只有空白区域出现在用户控件应该位于的表单中......