假设我们有一个代表
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 <</p>
class MyDelegateHelperClass{
public static void RemoveEventHandlers<TModel, TItem>(MulticastDelegate m, Expression<Func<TModel, TItem>> 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();