如何删除所有eventhandler
让我们说我们有一个代表
public delegate void MyEventHandler(string x);
和一个事件处理程序
public event MyEventHandler Something;
我们添加了多个事件..
for(int x = 0; x <10; x++) { this.Something += HandleSomething; }
我的问题是..如何从事件处理程序中删除所有方法,假设一个人不知道它已被添加10次(或更多或更少)次?
只需将事件设置为null
:
this.Something = null;
它将取消注册所有事件处理程序。
作为伪想法:
C#5 <
class MyDelegateHelperClass{ public static void RemoveEventHandlers(MulticastDelegate m, Expression> expr) { EventInfo eventInfo= ((MemberExpression)expr.Body).Member as EventInfo; Delegate[] subscribers = m.GetInvocationList(); Delegate currentDelegate; for (int i = 0; i < subscribers.Length; i++) { currentDelegate=subscribers[i]; eventInfo.RemoveEventHandler(currentDelegate.Target,currentDelegate); } } }
用法:
MyDelegateHelperClass.RemoveEventHandlers(MyDelegate,()=>myClass.myDelegate);
C#6
public static void RemoveEventHandlers(this MulticastDelegate m){ string eventName=nameof(m); EventInfo eventInfo=m.GetType().ReflectingType.GetEvent(eventName,BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); Delegate[] subscribers = m.GetInvocationList(); Delegate currentDelegate; for (int i = 0; i < subscribers.Length; i++) { currentDelegate=subscribers[i]; eventInfo.RemoveEventHandler(currentDelegate.Target,currentDelegate); } }
用法:
MyDelegate.RemoveEventHandlers();