您的位置:首页 > 编程语言 > C#

c#如何取得事件注册的方法

2008-06-05 15:15 363 查看
这个问题来自论坛,原文为如何判断事件已经被注册过?

用反射取出事件绑定的委托实例,然后用GetInvocationList就可以得到所有注册的方法了。

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace WindowsApplication19
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.Load+=new EventHandler(Form1_Load1);
this.Load+=new EventHandler(Form1_Load2);

PropertyInfo propertyInfo = (typeof(Form)).GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(this, null);
FieldInfo fieldInfo = (typeof(Form)).GetField("EVENT_LOAD", BindingFlags.Static | BindingFlags.NonPublic);

Delegate d = eventHandlerList[fieldInfo.GetValue(null)];

if (d != null)
{
foreach (Delegate de in d.GetInvocationList())
Console.WriteLine(de.Method.Name);
}
}
private void Form1_Load1(object sender, EventArgs e)
{
//什么也不干
}
private void Form1_Load2(object sender, EventArgs e)
{
//什么也不干
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: