如何取消注册表单事件的所有处理程序?

问题描述:

我有2个处理程序使用相同的形式。如何在添加新处理程序(C#)之前删除处理程序?如何取消注册表单事件的所有处理程序?

如果您在窗体本身的工作,你应该能够做这样的事情:

伪代码:

Delegate[] events = Form1.SomeEvent.GetInvokationList(); 

foreach (Delegate d in events) 
{ 
    Form1.SomeEvent -= d; 
} 

从形式,您SOL之外。

+6

我,你就可以访问该变量,只需将其设置为空 - 没有必要去通过调用列表... – 2008-11-13 17:58:01

如果您知道这些处理程序是什么,只需以与订阅它们相同的方式删除它们,除非使用 - =而不是+ =。

如果你不知道处理程序是什么,你不能删除它们 - 这个想法是事件封装可以防止一个感兴趣的团体在观察事件时阻止另一个类的兴趣。

编辑:我一直假设你正在讨论由不同的类实现的事件,例如,一个控件。如果您的课程“拥有”该事件,那么只需将相关变量设置为空。

我意识到这个问题相当古老,但希望它能帮助别人。您可以反省任何类的注销所有事件处理程序。

public static void UnregisterAllEvents(object objectWithEvents) 
{ 
    Type theType = objectWithEvents.GetType(); 

    //Even though the events are public, the FieldInfo associated with them is private 
    foreach (System.Reflection.FieldInfo field in theType.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)) 
    { 
     //eventInfo will be null if this is a normal field and not an event. 
     System.Reflection.EventInfo eventInfo = theType.GetEvent(field.Name); 
     if (eventInfo != null) 
     { 
      MulticastDelegate multicastDelegate = field.GetValue(objectWithEvents) as MulticastDelegate; 
      if (multicastDelegate != null) 
      { 
       foreach (Delegate _delegate in multicastDelegate.GetInvocationList()) 
       { 
        eventInfo.RemoveEventHandler(objectWithEvents, _delegate); 
       } 
      } 
     } 
    } 
}