问题
Lets say we have a delegate
public delegate void MyEventHandler(string x);
and an event handler
public event MyEventHandler Something;
we add multiple events..
for(int x = 0; x <10; x++)
{
this.Something += HandleSomething;
}
My question is .. how would one remove all methods from the eventhandler presuming one doesn't know its been added 10 (or more or less) times?
回答1:
Simply set the event to null
:
this.Something = null;
It will unregister all event handlers.
回答2:
As pseudo idea:
C#5 <
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);
}
}
}
Usage:
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);
}
}
Usage:
MyDelegate.RemoveEventHandlers();
来源:https://stackoverflow.com/questions/36084469/how-to-remove-all-eventhandler