-
c#中如何取行事件注册的方法
这个问题来自论坛,原文为如何判断事件已经被注册过?
用反射取出事件绑定的委托实例,然后用GetInvocationList就可以得到所有注册的方法了。
代码
view plaincopy to clipboardprint?
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Reflection;
namespaceWindowsApplication19
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
this.Load+=newEventHandler(Form1_Load1);
this.Load+=newEventHandler(Form1_Load2);
PropertyInfopropertyInfo=(typeof(Form)).GetProperty("Events",BindingFlags.Instance|BindingFlags.NonPublic);
EventHandlerListeventHandlerList=(EventHandlerList)propertyInfo.GetValue(this,null);
FieldInfofieldInfo=(typeof(Form)).GetField("EVENT_LOAD",BindingFlags.Static|BindingFlags.NonPublic);
Delegated=eventHandlerList[fieldInfo.GetValue(null)];
if(d!=null)
{
foreach(Delegatedeind.GetInvocationList())
Console.WriteLine(de.Method.Name);
}
}
privatevoidForm1_Load1(objectsender,EventArgse)
{
//什么也不干
}
privatevoidForm1_Load2(objectsender,EventArgse)
{
//什么也不干
}
}
}