我正在尝试在 VB.NET 中测试非常简单的事件处理。
到目前为止,我有:
Public Delegate Sub TestEventDelegate()
Public Event TestEvent As TestEventDelegate
Sub MySub
Raise TestEvent
End Sub
您将如何为上述仅显示简单的事件编写事件处理程序MessageBox
?
我正在尝试在 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
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.
在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