111,097
社区成员




PropertyInfo _PropertyInfo = p_Object.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
if (_PropertyInfo != null)
{
object _EventList = _PropertyInfo.GetValue(p_Object, null);
if (_EventList != null && _EventList is EventHandlerList)
{
EventHandlerList _List = (EventHandlerList)_EventList;
FieldInfo _FieldInfo = p_EventType.GetField(p_EventName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
if (_FieldInfo == null) return null;
Delegate _ObjectDelegate = _List[_FieldInfo.GetValue(p_Object)];
if (_ObjectDelegate == null) return null;
return _ObjectDelegate.GetInvocationList();
}
}
return null;
[/quote]
一个是反射,懂不懂?另一个涉及到WinForms的EventHandlerList机制,简单来说,因为对于控件来说,有大量的事件,为了减少存储提高性能,WinForms将它们全部存入一个列表,类似字典,这样绝大部分没有挂钩事件处理函数的事件就不要单独存储了。
实在不理解,你就当黑盒直接用吧。
PropertyInfo _PropertyInfo = p_Object.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
if (_PropertyInfo != null)
{
object _EventList = _PropertyInfo.GetValue(p_Object, null);
if (_EventList != null && _EventList is EventHandlerList)
{
EventHandlerList _List = (EventHandlerList)_EventList;
FieldInfo _FieldInfo = p_EventType.GetField(p_EventName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
if (_FieldInfo == null) return null;
Delegate _ObjectDelegate = _List[_FieldInfo.GetValue(p_Object)];
if (_ObjectDelegate == null) return null;
return _ObjectDelegate.GetInvocationList();
}
}
return null;
EventHandler pro;
pro = (sender, e) =>
{
//.......
};
button13.Click += pro;
如果要批量删除,可以像你现在这样用匿名委托。通过反射遍历找到它的所有事件,Remove掉