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

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

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

代码

view plaincopy to clipboardprint?
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)  
        {  
            //什么也不干  
        }  
    }  

 

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页