优化基本的单例模式
Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = Form2.Form2Single();//调用Form2中创建窗体的方法
frm2.Show();
}
}
}
Form2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form2 : Form
{
private Form2()
{
InitializeComponent();
}
private static Form2 form2 = null;
public static Form2 Form2Single()
{
if(form2==null)
{
form2 = new Form2();
}
return form2;
}
}
}
在Form2中如果采用
if(form2==null)
{
form2 = new Form2();
}
会出现在关闭窗体form2之后,再次点击按钮出现错误,frm2.Show();出现错误。关闭之后form2!=null,所以会出现错误;采用以下的判断就不会出现错误
if ((f22 == null) || (f22.IsDisposed))
{
f22 = new Form2();
}