反射-获取事件注册列表

说来很简单,GetType().GetField("事件名",BindingFlags.Instance | BindingFlags.NonPublic);

然后调用GetValue就可以得到对应的委托了。既然有委托了。调用GetInvokeList就可以了。

需要注意一点,vb.net的事件,反射时需要在事件名后面多写一个Event。不多说。分别贴出代码供参考和自己备用,虽然实在简单到不需要备份例子。以防万一吧。

c#

using System; using System.Reflection; namespace GetEventList { class Program { public class MyClass { public delegate void MyEventHandler(int value); public event MyEventHandler MyEvent; public void Foo() { if (MyEvent != null) MyEvent(88); } } static void Main(string[] args) { MyClass obj = new MyClass(); obj.MyEvent += delegate(int v) { Console.WriteLine(v); }; FieldInfo fi = obj.GetType().GetField("MyEvent", BindingFlags.Instance | BindingFlags.NonPublic); Delegate del = fi.GetValue(obj) as Delegate; if (del != null) { foreach (var item in del.GetInvocationList()) { Console.WriteLine(item.Method.ToString()); } } Console.ReadKey(); } } }

 

vb.net

Imports System.Reflection Module Module1 Sub Main() Dim obj As New EventTestClass '注册事件 AddHandler obj.MyEvent, Function(v As Integer) v + 1 '反射获取事件委托列表 Dim fi As FieldInfo = obj.GetType().GetField("MyEventEvent", BindingFlags.Instance Or BindingFlags.NonPublic) Dim del As System.Delegate = fi.GetValue(obj) '如果注册过,则不是Nothing If del Is Nothing Then Console.WriteLine("尚未注册事件") Else Console.WriteLine("注册事件了") End If Console.ReadKey() End Sub Public Class EventTestClass Public Delegate Sub MyEventHandler(ByVal value As Integer) Public Event MyEvent As MyEventHandler Public Sub Foo() RaiseEvent MyEvent(88) End Sub End Class End Module

你可能感兴趣的:(function,Module,null,Integer,Class,VB.NET)