作爲僞想法:
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);
}
}
}
用法:
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();
我一直以爲一個人不得不手動刪除它們,但令人驚訝的是..這確實工作..我做了類似於http://stackoverflow.com/questions/447821/how-doi-i-取消訂閱所有處理程序從一個事件爲特殊類在C – Eminem
在我看來,這種做法是值得做一個類的Dispose(布爾)方法,但我沒有請參閱任何地方的此練習參考。我的想法是什麼? –
我認爲這可能是一個好主意,但你應該小心,不要臃腫你的代碼,這可能最終導致錯誤,而不是修復它們。我有一個方法,我通過註冊和取消註冊操作,並調用「Dispose」它執行所有註銷操作。 @PieterGeerkens –