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