如何从一个event事件的委托列表上移除事件

     前些天有同事问我怎么从一个Button的Click事件中移除所有委托,我想了一下可以这样来做:

public   void  RemoveEvent(Control c)
{
    PropertyInfo propertyInfo 
=  ( typeof (System.Windows.Forms.Button)).GetProperty( " Events " , BindingFlags.Instance  |  BindingFlags.NonPublic);
    EventHandlerList eventHandlerList 
=  (EventHandlerList)propertyInfo.GetValue(c,  null );
    FieldInfo fieldInfo 
=  ( typeof (Control)).GetField( " EventClick " , BindingFlags.Static  |  BindingFlags.NonPublic);
    Delegate d 
=  eventHandlerList[fieldInfo.GetValue( null )];
    
if  (d  !=   null )
    {
        
foreach  (Delegate temp  in  d.GetInvocationList())
        {

            c.Click 
-=  (EventHandler)temp;
        }
     } 
}

      基本原理还是通过反射来做,获取字段的委托列表后再进行处理((EventHandlerList)propertyInfo.GetValue(c, null)可以获取委托列表),通过Reflector可以看到如下信息: 

     


转载于:https://www.cnblogs.com/vivounicorn/archive/2009/06/24/1510328.html

猜你喜欢

转载自blog.csdn.net/weixin_33711647/article/details/93642147