怎么控制一个委托事件里同样的方法只注册一次
大家好,请教大家一个问题。我有一个单例窗体如 Fax:Form 里面定义了一个委托事件
C# code
public delegate void UpdateFaxEventHander(string tifPath);
public event UpdateFaxEventHander UpdateFax;
此事件在另一个窗体的构造函数里被注册如:
C# code
public FrmFaxTaskEdit()
{
InitializeComponent();
Fax.Instance.UpdateFax += new Fax.UpdateFaxEventHander(Instance_UpdateFax);
}
在我每次实例化FrmFaxTaskEdit 时都会给Fax.Instance.UpdateFax 注册Instance_UpdateFax 这个方法。
想请教下大家 有什么判断条件可以控制 Instance_UpdateFax 只被UpdateFax这个事件注册一次。
注:不想在窗体的Closed事件中注销这个事件的方法,因为FrmFaxTaskEdit可能会被打开多个。这样也起不到作用。
请教啦!
------解决方案-------------------- if(Fax.Instance.UpdateFax == null)
{
Fax.Instance.UpdateFax += new Fax.UpdateFaxEventHander(Instance_UpdateFax);
}
------解决方案-------------------- 用事件访问器。
在add和remove里面写自己的逻辑就行了。
------解决方案-------------------- 事件注册不放在构造函数中,定义一个方法来注册,这样你可以在代码中控制什么情况下注册
------解决方案--------------------
OK,搞定了,代码如下:
Fax.Instance.UpdateFax += new Fax.UpdateFaxEventHander(Instance_UpdateFax);
if (!Fax.Instance.UpdateFax.GetInvocationList().Contains((UpdateFaxEventHander)Instance_UpdateFax))
{
UpdateFax += new UpdateFaxEventHander(Instance_UpdateFax);
}
-------------
解释一下,这个GetInvocationList()可以获取委托链,就是说你绑定了哪些函数要执行。 在这个委托链中判断下是否已经添加就可以了。
------解决方案-------------------- 探讨 Fax.Instance.UpdateFax += new Fax.UpdateFaxEventHander(Instance_UpdateFax); 改为: if (!Fax.Instance.UpdateFax.GetInvocationList().Contains((Fax.UpdateFaxEventHander)Instance_UpdateFax)) { Fax.Inst……
------解决方案--------------------
这样就可以了:
C# code
Delegate[] allDlg = new Delegate[this.UpdateFax.GetInvocationList().GetLength(0)];
this.UpdateFax.GetInvocationList().CopyTo(allDlg, 0);
foreach (Delegate dlg in allDlg)
{
if (dlg.Method.Name == "Form1_UpdateFax")
{
//不在绑定
}
else
{
//绑定
UpdateFax += new UpdateFaxEventHander(Form1_UpdateFax);
MessageBox.Show("绑定成功");
}
}
------解决方案-------------------- 探讨 引用: Fax.Instance.UpdateFax += new Fax.UpdateFaxEventHander(Instance_UpdateFax); if (!Fax.Instance.UpdateFax.GetInvocationList().Contains((Fax.UpdateFaxEventHander)Instance_UpdateFa……
------解决方案-------------------- 用单例模式 如下:C# code
class Program
{
static void Main(string[] args)
{
pokeer pk = pokeer.GetIntence();
}
}
class pokeer
{
private readonly static object pkLog = new object();
private static pokeer pk = null;
private pokeer()
{
}
public static pokeer GetIntence()
{
if (pk == null)
{
lock (pkLog)
{
if (pk == null)
{
pk = new pokeer();
}
}
}
return pk;
}
}