查找给定对象的所有侦听器

时间:2010-11-17 19:09:51

标签: vb.net events reflection event-handling

我有一个对象(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

2 个答案:

答案 0 :(得分:1)

使用基类型,您将获得所有事件,但只有实际使用包含具有侦听方法的委托的私有支持字段的事件。如果他们不这样做(例如,考虑WPF的路由事件),我认为你运气不好:既然custom events可以有AddHandler,RemoveHandler和RaiseEvent的任意实现,我不会认为有一种通用的方法来获取监听方法列表(因为可能没有这样的列表)。

答案 1 :(得分:0)

得到了 - 我的坏。

我所要做的就是用对象的基本类型调用相同的子。

相关问题