单件模式+打开窗体+窗体构造函数参数
2020-12-12 23:34
标签:des style blog class c tar 利用单件模式避免重复打开窗体,窗体为无参数构造函数模式。 注:该博客中有自动关闭窗体的方法 http://www.cnblogs.com/zfanlong1314/p/3567308.html 为了打开窗体时传入参数,可以改变方法的传递参数,本人修改后代码如下 ///
///
//加上实例关闭事件,窗体就会自动回收,即instance=null; 这样修改可以避免重复打开窗体,且能传递参数。但是如果一个窗体有多个构造函数时就只能打开一个实例。 搜到如下解决方案,但是对func http://bbs.csdn.net/topics/360165634 该帖子的最后解决方法是:将你的G_ public class SingletonGenerator public SingletonGenerator(Func public T Value return this.instance; 单件模式+打开窗体+窗体构造函数参数,搜素材,soscw.com 单件模式+打开窗体+窗体构造函数参数 标签:des style blog class c tar 原文地址:http://www.cnblogs.com/maggie/p/3738347.html
///
泛型实现窗体实例单件化
///
///
public static class Singleton
{
private static T
instance = default(T);
private static readonly object lockHelper = new
object();
///
获取窗体的唯一实例
///
/// 构造函数参数
///
public static T Instance(object[] args)
{
if (instance == null)
{
lock (lockHelper)
{
if (instance == null)
{
instance =
(T)Activator.CreateInstance(typeof(T), args);
instance.FormClosed
+= new FormClosedEventHandler(DestroyForm);
}
}
}
return
instance;
}
///
///
当窗体关闭时将Instance置空
///
///
///
private static void
DestroyForm(object sender, FormClosedEventArgs e)
{
instance = default(T);
}
{
private object locker;
private bool initialized =
false;
private Func
private T
instance;
{
initialized = false;
func =
funcParam;
locker = new object();
}
{
get
{
if (!this.initialized)
{
lock (this.locker)
{
if (!this.initialized)
{
this.instance =
this.func();
this.initialized =
true;
}
}
}
}
}
}