Is there a way to know in VB.NET if a handler has been registered for an event?

前端 未结 6 1240
难免孤独
难免孤独 2021-01-17 14:07

In C# I can test for this...

public event EventHandler Trigger;
protected void OnTrigger(EventArgs e)
{
    if (Trigger != null)
        Trigger(this, e);
}
         


        
6条回答
  •  醉话见心
    2021-01-17 14:28

    There is an interesting discussion in question 1129517 around how to do this very thing in C#.

    Since the class that contains the Event was written in C#, the delegate semantics do apply, and those techniques should work for you. However, you'll need to translate the source to VB.NET for your unit test.

    Given the following class in a C# assembly:

    public class Triggerific
    {
        public event EventHandler Trigger;
    
        private static void OnTriggerTriggered(object sender, EventArgs e)
        {
            Console.WriteLine("Triggered!");
        }
    
        public void AddTrigger()
        {
            Trigger += OnTriggerTriggered;
        }
    }
    

    Here is some VB.NET code which will correctly determine if a handler was registered for the Trigger event:

     _
    Public Sub TriggerTest()
        Dim cut As New Triggerific
        cut.AddTrigger()
    
        Assert.IsNotNull(GetEventHandler(cut, "Trigger"))
    End Sub
    
    Private Shared Function GetEventHandler(ByVal classInstance As Object, ByVal eventName As String) As EventHandler
        Dim classType As Type = classInstance.[GetType]()
        Dim eventField As FieldInfo = classType.GetField(eventName, BindingFlags.GetField Or BindingFlags.NonPublic Or BindingFlags.Instance)
    
        Dim eventDelegate As EventHandler = DirectCast(eventField.GetValue(classInstance), EventHandler)
    
        ' eventDelegate will be null/Nothing if no listeners are attached to the event
        Return eventDelegate
    End Function
    

提交回复
热议问题