我正在尝试编写一个通用函数,给出对控件/组件的引用以及在其类上声明的事件的名称,它应该能够检索(通过反射) 当前为指定事件名称注册的所有事件处理程序。
我遇到的第一个也是主要问题(已解决,因此您可以忽略本段)是我在 StackOverflow 中找到的所有解决方案(主要是用 C# 编写的)都仅限于作者仅查找事件的含义 -中的字段声明System.Windows.Forms.Control
类,因此会失败,例如在尝试检索事件处理程序时System.Windows.Forms.ToolStripMenuItem.MouseEnter
事件(因为事件字段是在System.Windows.Forms.ToolStripItem
类),并且也不考虑事件字段命名System.Windows.Forms.Form
类,其中有一个下划线。
所以我涵盖了所有这些,目前我的解决方案适用于(或者我认为它适用于)继承自的任何类System.ComponentModel.Component
.
我现在遇到的唯一问题是当我声明一个自定义类型(继承自Control / 用户控制 / 成分 / Form等),然后我将该类型传递给我的函数。在这种情况下,我遇到了空引用异常。不知道我在这里做错了什么......
Public Shared Function GetEventHandlers(component As IComponent, eventName As String) As IReadOnlyCollection(Of [Delegate])
Dim componentType As Type
Dim declaringType As Type ' The type on which the event is declared.
Dim eventInfo As EventInfo
Dim eventField As FieldInfo = Nothing
Dim eventFieldValue As Object
Dim eventsProp As PropertyInfo
Dim eventsPropValue As EventHandlerList
Dim eventDelegate As [Delegate]
Dim invocationList As [Delegate]()
' Possible namings for an event field.
Dim eventFieldNames As String() =
{
$"Event{eventName}", ' Fields declared in 'System.Windows.Forms.Control' class.
$"EVENT_{eventName.ToUpper()}", ' Fields declared in 'System.Windows.Forms.Form' class.
$"{eventName}Event" ' Fields auto-generated.
}
Const bindingFlagsEventInfo As BindingFlags =
BindingFlags.ExactBinding Or
BindingFlags.Instance Or
BindingFlags.NonPublic Or
BindingFlags.Public Or
BindingFlags.Static
Const bindingFlagsEventField As BindingFlags =
BindingFlags.DeclaredOnly Or
BindingFlags.ExactBinding Or
BindingFlags.IgnoreCase Or
BindingFlags.Instance Or
BindingFlags.NonPublic Or
BindingFlags.Static
Const bindingFlagsEventsProp As BindingFlags =
BindingFlags.DeclaredOnly Or
BindingFlags.ExactBinding Or
BindingFlags.Instance Or
BindingFlags.NonPublic
Const bindingFlagsEventsPropValue As BindingFlags =
BindingFlags.Default
componentType = component.GetType()
eventInfo = componentType.GetEvent(eventName, bindingFlagsEventInfo)
If (eventInfo Is Nothing) Then
Throw New ArgumentException($"Event with name '{eventName}' not found in type '{componentType.FullName}'.", NameOf(eventName))
End If
declaringType = eventInfo.DeclaringType
For Each name As String In eventFieldNames
eventField = declaringType.GetField(name, bindingFlagsEventField)
If (eventField IsNot Nothing) Then
Exit For
End If
Next name
If (eventField Is Nothing) Then
Throw New ArgumentException($"Field with name 'Event{eventName}', 'EVENT_{eventName.ToUpper()}' or '{eventName}Event' not found in type '{declaringType.FullName}'.", NameOf(eventName))
End If
#If DEBUG Then
Debug.WriteLine($"Field with name '{eventField.Name}' found in type '{declaringType.FullName}'")
#End If
eventFieldValue = eventField.GetValue(component)
eventsProp = GetType(Component).GetProperty("Events", bindingFlagsEventsProp, Type.DefaultBinder, GetType(EventHandlerList), Type.EmptyTypes, Nothing)
eventsPropValue = DirectCast(eventsProp.GetValue(component, bindingFlagsEventsPropValue, Type.DefaultBinder, Nothing, CultureInfo.InvariantCulture), EventHandlerList)
eventDelegate = eventsPropValue.Item(eventFieldValue)
invocationList = eventDelegate.GetInvocationList()
If (invocationList Is Nothing) Then ' There is no event-handler registered for the specified event.
Return Enumerable.Empty(Of [Delegate]).ToList()
End If
Return invocationList
End Function
异常发生在这一行:
invocationList = eventDelegate.GetInvocationList()
because eventDelegate
一片空白。
要测试异常,可以以此类为例:
Public Class TestUserControl : Inherits UserControl
Event TestEvent As EventHandler(Of EventArgs)
Overridable Sub OnTestEvent(e As EventArgs)
If (Me.TestEventEvent IsNot Nothing) Then
RaiseEvent TestEvent(Me, e)
End If
End Sub
End Class
和这样的示例用法:
Dim ctrl As New TestUserControl()
AddHandler ctrl.TestEvent, Sub()
Debug.WriteLine("Hello World!")
End Sub
Dim handlers As IReadOnlyCollection(Of [Delegate]) =
GetEventHandlers(ctrl, NameOf(TestUserControl.TestEvent))
For Each handler As [Delegate] In handlers
Console.WriteLine($"Method Name: {handler.Method.Name}")
Next
不确定这是否是与绑定标志相关的问题,或者可能是与事件字段命名相关的问题...但在尝试与公开的任何内置控件/组件类相同时,我没有这个空引用对象问题事件,而不是那个TestUserControl
class.
我做错了什么?以及如何解决?请注意,此功能仍然应该是通用的。