我正在尝试在VB.NET.中测试非常简单的事件处理
到目前为止,我有:
Public Delegate Sub TestEventDelegate()
Public Event TestEvent As TestEventDelegate
Sub MySub
Raise TestEvent
End Sub
您将如何为上面刚刚显示一个简单MessageBox
的事件编写一个事件处理程序?
编写处理程序方法很简单——只需编写一个不带参数并显示消息框的Sub
。
然后,您需要为事件订阅处理程序,您可以在方法中添加Handles
子句:
Sub ShowMessageBox() Handles foo.TestEvent
或者使用AddHandler
语句:
AddHandler foo.TestEvent, AddressOf ShowMessageBox
请注意,为了遵循.NET约定,您的委托应该有两个参数——一个类型为Object
,用于指定引发事件的对象,另一个类型是EventArgs
或子类,用于提供任何额外信息。这不是语言所要求的,但它是一个广泛遵循的惯例。
在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