How to write event handler in VB.NET?

2019-03-01 08:55发布

问题:

I am trying to test out very simple event handling in VB.NET.

So far I have:

Public Delegate Sub TestEventDelegate()
Public Event TestEvent As TestEventDelegate

Sub MySub
    Raise TestEvent
End Sub

How would you write an event handler for the above event that just displayed a simple MessageBox?

回答1:

Writing the handler method is simple - just write a Sub which takes no parameters and displays a message box.

You then need to subscribe the handler to the event, which you can either do adding a Handles clause to the method:

Sub ShowMessageBox() Handles foo.TestEvent

Or by using an AddHandler statement:

AddHandler foo.TestEvent, AddressOf ShowMessageBox

Note that to follow .NET conventions, your delegate should have two parameters - one of type Object to specify which object raised the event, and one of type EventArgs or a subclass, to provide any extra information. This isn't required by the language, but it's a broadly-followed convention.



回答2:

In VB, we have two methods to subscribe the event of Publisher class.

'Delegate
Public Delegate Sub TestEventDelegate()

'Event publisher class that publishes and raises an event

Public Class EventPublisher
    Private _num As Integer
    Public Event NumberChanged As TestEventDelegate
    Public Property Number As Integer
        Get
            Return _num
        End Get
        Set(value As Integer)
            _num = value
            RaiseEvent NumberChanged()
        End Set
    End Property
End Class

'Event subscriber class

Public Class EventSubscriber
    'instance of EventPublisher class
    Private WithEvents myObject As New EventPublisher

    'Handler of myObject.NumberChanged event
    Public Sub ShowMessage() Handles myObject.NumberChanged
        Console.WriteLine("Value has been changed")
    End Sub

    Shared Sub Main()
        Dim es As New EventSubscriber
        es.myObject.Number = 10
        es.myObject.Number = 20

        'Handle the events dynamically using AddHandler
        Dim ep1 As New EventPublisher
        ep1.Number = 101
        'Attach an event to the handler
        AddHandler ep1.NumberChanged, AddressOf TestIt
        ep1.Number = 102
    End Sub
    Shared Sub TestIt()
        Console.WriteLine("Number is modified")
    End Sub
End Class