前些天有同事问我怎么从一个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可以看到如下信息: 

 

     

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

相关文章:

  • 2021-11-25
  • 2022-03-04
  • 2022-12-23
  • 2021-09-17
  • 2021-09-17
  • 2022-12-23
猜你喜欢
  • 2022-03-11
  • 2022-12-23
  • 2021-09-17
  • 2021-09-12
  • 2022-12-23
  • 2022-12-23
  • 2022-02-05
相关资源
相似解决方案