首页 > 其他 > 详细

通过反射处理委托

时间:2014-12-04 20:08:12      阅读:268      评论:0      收藏:0      [点我收藏+]

首先要确定处理的是哪一种事件或者委托(这里选用常用的 Click 事件)

FieldInfo fieldInfo = (typeof(Control)).GetField

("EventClick", BindingFlags.Static | BindingFlags.NonPublic);

然后获取事件列表 (这里使用的 Button )

 EventHandlerList buttonEvents = (EventHandlerList)this.button1.GetType().InvokeMember("Events",
System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Instance |
 System.Reflection.BindingFlags.NonPublic
                , null, this.button1, null);

拆开写成俩行或许更容易看

PropertyInfo propertyInfo = (typeof(System.Windows.Forms.Button)).GetProperty("Events",
 BindingFlags.Instance | BindingFlags.NonPublic);
EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(button1, null);

可以通过反射从对象中获取所需的属性信息。这里就是 从 Button控件中获取事件的信息,事件的属性列表中键值为 “Events”,然后拆箱为 EventHandlerList 对象。

然后从事件列表中获取全部的属于我们处理的事件类型的委托。

// 得到 EventClick 事件的键值表示
object eventKey = fieldInfo.GetValue(null);

// 得到所有事件

Delegate d = eventHandlerList[eventKey];

下面就是可以通过循环来处理了

if (d != null)
{
 foreach (Delegate temp in d.GetInvocationList())
 {
  Console.WriteLine(temp.Method.Name);
  //这个地方可以清除所有的委托,也可以使用条件清除指定委托,没有办法直接清除所有的

  richTextBox1.AppendText(temp.Method.Name + "\n");
  // 清理委托
  eventHandlerList.RemoveHandler(eventKey, temp);
 }
}

CodeDemo

通过反射处理委托

原文:http://my.oschina.net/HenuToater/blog/352380

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!