Winform 窗体单例
有窗体Form1和窗体Form2,单击Form1上按钮,只弹出一个Form2。
Form2里自定义一个方法,里面判断是否弹出Form2,没有时弹出Form2。
1 public static Form2 instance; 2 public static Form2 CreateForm() 3 { 4 if (instance == null || instance.IsDisposed) 5 { 6 instance = new Form2(); 7 } 8 return instance; 9 }
Form1里用Form2的CreateForm()方法实例化Form2,
1 Form2 f2 = Form2.CreateForm();
泛型形式:
public class Form_Singleton<T> where T : Form, new() { //private static T t_Form = null; public static T t_Form { get; set; } public static T CreateForm() { if (t_Form == null || t_Form.IsDisposed) { t_Form = new T(); } return t_Form; } }
调用:
Form2 f2 = Form_Singleton<Form2>.CreateForm();
相关参考: