`
csstome
  • 浏览: 1478255 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

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

阅读更多

这个问题来自论坛,原文为如何判断事件已经被注册过?

用反射取出事件绑定的委托实例,然后用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)
        {
            //什么也不干
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics