我正在尝试编写一个通用函数,给定对控件/组件的引用以及在其类上声明的事件的名称,它应该能够(通过Reflection)检索当前为指定对象注册的所有事件处理程序。事件名称。
我遇到的第一个也是主要的问题(已解决,因此您可以忽略本段),这是我在StackOverflow中找到的所有解决方案(主要是用C#编写)的局限性,即作者仅查找事件-类中的字段声明System.Windows.Forms.Control
,因此例如在尝试检索事件的事件处理程序时将失败System.Windows.Forms.ToolStripMenuItem.MouseEnter
(因为在System.Windows.Forms.ToolStripItem
类中声明了事件字段),并且也未考虑System.Windows.Forms.Form
类的事件字段命名,其中有下划线。因此,我涵盖了所有这些内容,目前,我的解决方案适用于(继承自)任何类System.ComponentModel.Component
。
我现在遇到的唯一问题是当我声明一个自定义类型(该类型继承自Control / UserControl / Component / 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()
因为eventDelegate
为null。
要测试异常,可以以此类为例:
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
该类。
我做错了什么?如何解决?请注意,此功能仍应是通用的。
感谢@ Hans Passant在主要问题的评论中建议的内容,此方法可以正常工作:
Public Function GetEventHandlers(component As IComponent, eventName As String) As IReadOnlyCollection(Of [Delegate])
Dim componentType As Type = component.GetType()
' Find event declaration in the source type.
Dim eventInfo As EventInfo = componentType.GetEvent(eventName, BindingFlags.ExactBinding Or BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Static)
If (eventInfo Is Nothing) Then
Throw New ArgumentException($"Event with name '{eventName}' not found in type '{componentType.FullName}'.", NameOf(eventName))
End If
' The type on which the event is declared.
Dim declaringType As Type = eventInfo.DeclaringType
' Find event-field declaration in the declaring type.
Dim eventField As FieldInfo = Nothing
' 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) declared in other classes.
}
For Each name As String In eventFieldNames
eventField = declaringType.GetField(name, BindingFlags.DeclaredOnly Or BindingFlags.ExactBinding Or BindingFlags.IgnoreCase Or BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.Static)
If (eventField IsNot Nothing) Then
Exit For
End If
Next name
If (eventField Is Nothing) Then
Throw New ArgumentException($"Field with name '{String.Join("' or '", eventFieldNames)}' not found in declaring type '{declaringType.FullName}'.", NameOf(eventName))
End If
#If DEBUG Then
Debug.WriteLine($"Field with name '{eventField.Name}' found in declaring type '{declaringType.FullName}'")
#End If
Dim eventFieldValue As object = eventField.GetValue(component)
If TypeOf eventFieldValue Is MulticastDelegate
' See @Hans Passant comment:
' https://stackoverflow.com/questions/56763972/get-all-the-event-handlers-of-a-event-declared-in-a-custom-user-control?noredirect=1#comment100177090_56763972
Return DirectCast(eventFieldValue, MulticastDelegate).GetInvocationList()
End If
Dim eventsProp As PropertyInfo = GetType(Component).GetProperty("Events", BindingFlags.DeclaredOnly Or BindingFlags.ExactBinding Or BindingFlags.Instance Or BindingFlags.NonPublic, Type.DefaultBinder, GetType(EventHandlerList), Type.EmptyTypes, Nothing)
Dim eventsPropValue As EventHandlerList = DirectCast(eventsProp.GetValue(component, BindingFlags.Default, Type.DefaultBinder, Nothing, CultureInfo.InvariantCulture), EventHandlerList)
Dim eventDelegate As [Delegate] = eventsPropValue.Item(eventFieldValue)
Dim invocationList As [Delegate]() = 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
我们还可以为EventInfo类型定义下一个方法扩展,以充当EventInfo.RemoveEventHandler(Object,Delegate)的方法重载:
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Removes an event handler from an event source.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Public Class Form1
'''
''' Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Shown
''' Dim target As Form = Me
''' Dim eventInfo As EventInfo = target.GetType().GetEvent(NameOf(Form.Click))
''' eventInfo.RemoveEventHandler(target, NameOf(Me.Form1_Click))
''' End Sub
'''
''' Private Sub Form1_Click(sender As Object, e As EventArgs) Handles MyBase.Click
''' MsgBox(MethodBase.GetCurrentMethod().Name)
''' End Sub
'''
''' End Class
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <param name="eventInfo">
''' The event information.
''' </param>
'''
''' <param name="target">
''' The event source.
''' </param>
'''
''' <param name="handlerName">
''' The name of the delegate to be disassociated from the events raised by <paramref name="target"/>.
''' <para></para>
''' Note that the name is case-sensitive.
''' </param>
''' ----------------------------------------------------------------------------------------------------
<Extension>
Public Sub RemoveEventHandler(eventInfo As EventInfo, target As IComponent, handlerName As String)
If String.IsNullOrWhiteSpace(handlerName)
Throw New ArgumentNullException(NameOf(handlerName))
End If
For each handler As [Delegate] in GetEventHandlers(target, eventInfo.Name)
If handler.Method.Name.Equals(handlerName, StringComparison.Ordinal)
eventInfo.RemoveEventHandler(target, handler)
Exit Sub
End If
Next handler
Throw New ArgumentException($"No delegate was found with the specified name: '{handlerName}'", NameOf(handlerName))
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句