通过反射处理委托

摘要 委托不能够想事件那样使用 -= 移除事件,那么如何动态地移除事件呢?.Net 提供的运行时反射机制可以完成这个目的。

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

?

1

2

3

FieldInfo fieldInfo = (typeof(Control)).GetField

   

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

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

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

1

2

3

PropertyInfo propertyInfo = (typeof(System.Windows.Forms.Button)).GetProperty("Events",

 BindingFlags.Instance | BindingFlags.NonPublic);

EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(button1, null);

 

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

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

?

1

2

3

4

5

6

// 得到 EventClick 事件的键值表示

object eventKey = fieldInfo.GetValue(null);

   

// 得到所有事件

   

Delegate d = eventHandlerList[eventKey];

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

?

1

2

3

4

5

6

7

8

9

10

11

12

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

posted @ 2014-12-06 14:43  涛褪荒芜  阅读(130)  评论(0)    收藏  举报