处理来自其他班级的某些事件

时间:2018-11-28 06:44:32

标签: vb.net

我正在使用具有以下功能的类:

Private _players As New List(Of Player)

Public Sub PlayerAdd(ByVal name As String, ByVal money As Decimal)
        _players.Add(New Player With {
                     .name = name,
                     .money = money})
    End Sub

当从另一个类调用此子程序时,我希望能够捕获此事件并运行其他代码,如下所示:

Public foo As New MyCustomClass

Private Sub test Handles foo.PlayerAdded
' Code I want to run here.
End Sub

我知道我不能那样做,但这只是为了展示我要完成的工作。做这样的事情的最好方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以按照以下步骤进行操作:

Public Class MyCustomClass

    Private _players As New List(Of Player)
    Public Event PlayerAdded()

    Public Sub PlayerAdd(ByVal name As String, ByVal money As Decimal)
        _players.Add(New Player With {
                 .name = name,
                 .money = money})
        RaiseEvent PlayerAdded()
    End Sub

End Class

然后您可以从另一个类中对该事件进行侦听:

AddHandler foo.PlayerAdded, AddressOf <SomeSub> ' To catch the event