如何在VB.NET中编写事件处理程序?




events event-handling (2)

我试图在VB.NET中测试非常简单的事件处理。

到目前为止我有:

Public Delegate Sub TestEventDelegate()
Public Event TestEvent As TestEventDelegate

Sub MySub
    Raise TestEvent
End Sub

你将如何编写上述事件的事件处理程序,只是显示一个简单的MessageBox


在VB中,我们有两种方法来订阅Publisher类的事件。

'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

编写处理程序方法很简单 - 只需编写一个不带参数的Sub并显示一个消息框。

然后,您需要为事件订阅处理程序,您可以向该方法添加Handles子句:

Sub ShowMessageBox() Handles foo.TestEvent

或者使用AddHandler语句:

AddHandler foo.TestEvent, AddressOf ShowMessageBox

请注意,遵循.NET约定,您的委托应该有两个参数 - 一个用于指定哪个对象引发事件的Object类型,另一个用于提供任何额外信息的EventArgs类型或子类。 这不是语言所要求的,但是这是一个广泛遵循的惯例。







visual-studio-2005