单例中为防止多处注册事件引起异步触发时发生报错,网上找了一圈没找到想要的方法。
【异常类型】:ArgumentException
【异常信息】:该委托必须有一个目标(且仅有一个目标)。
结合网上资料整合了个方法
/// <summary> /// 移除所有注册事件 /// </summary> public void RemoveAllEvent() { var newType = this.GetType(); foreach (var item in newType.GetEvents()) { FieldInfo _Field = newType.GetField(item.Name, BindingFlags.Instance | BindingFlags.NonPublic); if (_Field != null) { object _FieldValue = _Field.GetValue(this); if (_FieldValue != null && _FieldValue is Delegate) { Delegate _ObjectDelegate = (Delegate)_FieldValue; Delegate[] invokeList = _ObjectDelegate.GetInvocationList(); if (invokeList != null) { foreach (Delegate del in invokeList) { item.RemoveEventHandler(this, del); } } } } } }
测试:
using System; using System.Reflection; namespace FormTest { class Class1 { public event Action OnTest; public event Action OnShow; /// <summary> /// 移除所有注册事件 /// </summary> public void RemoveAllEvent() { var newType = this.GetType(); foreach (var item in newType.GetEvents()) { FieldInfo _Field = newType.GetField(item.Name, BindingFlags.Instance | BindingFlags.NonPublic); if (_Field != null) { object _FieldValue = _Field.GetValue(this); if (_FieldValue != null && _FieldValue is Delegate) { Delegate _ObjectDelegate = (Delegate)_FieldValue; Delegate[] invokeList = _ObjectDelegate.GetInvocationList(); if (invokeList != null) { foreach (Delegate del in invokeList) { item.RemoveEventHandler(this, del); } } } } } } } }
private void button7_Click(object sender, EventArgs e) { Class1 cla = new Class1(); cla.OnShow += cla_OnShow; cla.OnShow += cla_OnShow; cla.OnTest += cla_OnTest; cla.RemoveAllEvent(); } void cla_OnTest() { throw new NotImplementedException(); } void cla_OnShow() { throw new NotImplementedException(); }