我有一个对象(myObject),我试图找到任何正在侦听该对象的任何事件的东西。查找给定对象的所有侦听器
下面的代码似乎按照预期为使用AddHandler语法创建的侦听器工作;但不会报告使用“句柄”语法创建的侦听器。
编辑︰看来我是不正确的。无论使用AddHandler/Handles语法,此代码都可以工作。但它似乎只适用于该对象的自定义事件。如果myObject是一个控件 - 我永远不会看到Load()事件处理程序;但我会看到“MyCustomEvent”的处理程序。
任何人都可以告诉我我需要做些什么来获得这些事件吗?
Public Sub GetListeners(ByVal myObject As Object)
Dim myType As Type = myObject.GetType
Dim myFieldList As FieldInfo() = myType.GetFields(BindingFlags.Static Or BindingFlags.Instance Or BindingFlags.NonPublic)
For Each myInfo In myFieldList
Dim myDelegate As [Delegate] = TryCast(myInfo.GetValue(myObject), [Delegate])
If myDelegate IsNot Nothing Then
For Each myItem In myDelegate.GetInvocationList
System.Diagnostics.Debug.WriteLine(myDelegate.GetInvocationList(0).Method.Name & "-->" & myDelegate.GetInvocationList(0).Method.DeclaringType.FullName)
Next
End If
Try
Dim eventList As EventHandlerList = DirectCast(myObject.GetType().GetProperty("Events", _
(BindingFlags.FlattenHierarchy Or (BindingFlags.NonPublic Or BindingFlags.Instance))).GetValue(myObject, Nothing), EventHandlerList)
myDelegate = eventList(myInfo.GetValue(myObject))
Catch ex As Exception
End Try
If myDelegate IsNot Nothing Then
For Each myItem In myDelegate.GetInvocationList
System.Diagnostics.Debug.WriteLine(myDelegate.GetInvocationList(0).Method.Name & "-->" & myDelegate.GetInvocationList(0).Method.DeclaringType.FullName)
Next
End If
Next
End Sub
这也应该处理'Handles'的情况,因为这只是'AddHandler'的语法糖。也许你还没有用相关的'Handles'子句创建一个类的对象? – cdhowie 2010-11-17 19:22:03