c# 移除类中所有事件的绑定
https://www.cnblogs.com/zszh/p/11321005.html
单例中为防止多处注册事件引起异步触发时发生报错,网上找了一圈没找到想要的方法。
【异常类型】: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); } } } } } }
静态类方法
/// <summary> /// 移除此静态类指定事件名称的所有事件绑定 /// </summary> /// <param name="eventname"></param> public static void RemoveAllEvent(string eventname) { System.Reflection.FieldInfo _Field = typeof(GlobalVariables).GetField(eventname, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); if (_Field != null) { object _FieldValue = _Field.GetValue(typeof(GlobalVariables)); if (_FieldValue != null && _FieldValue is Delegate) { Delegate _ObjectDelegate = (Delegate)_FieldValue; Delegate[] invokeList = _ObjectDelegate.GetInvocationList(); if (invokeList != null) { foreach (var item in typeof(GlobalVariables).GetEvents()) { if (item.Name == eventname) { foreach (Delegate del in invokeList) { item.RemoveEventHandler(typeof(GlobalVariables), del); } break; } } } } } }
测试:
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(); }