我究竟做错了什么? - Visual Basic事件

时间:2013-09-05 22:25:23

标签: vb.net events event-handling c#-to-vb.net

我知道我的问题很简单,但我无法弄清楚我的代码有什么问题。我有这个Head First C#书,我在VB.NET中转换了代码。我期望在单击表单中的按钮后调用catches类的Pitcher子例程。但没有任何反应。

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim myBall As New Ball
        Dim pitcher As New Pitcher
        myBall.OnBallInPlay(New BallEventArgs(10, 20))
    End Sub
End Class

Public Class Ball
    Public Event BallInPlay(ByVal sender As Object, ByVal e As BallEventArgs)
    Public Sub OnBallInPlay(ByVal e As BallEventArgs)
        RaiseEvent BallInPlay(Me, e)
    End Sub
End Class

Public Class BallEventArgs
    Inherits EventArgs
    Dim trajectory As Integer
    Dim distance As Integer
    Public Sub New(ByVal trajectory As Integer, ByVal distance As Integer)
        Me.trajectory = trajectory
        Me.distance = distance
    End Sub
End Class

Public Class Pitcher
    Public WithEvents mySender As Ball

    Public Sub catches(ByVal sender As Object, ByVal e As EventArgs) Handles mySender.BallInPlay
        MessageBox.Show("Pitcher: ""I catched the ball!""")
    End Sub
End Class

在调用Ball.OnBallInPlay后,Pitcher.catches将会收听。不是吗,还是我错过了一些明显而重要的东西?

2 个答案:

答案 0 :(得分:2)

您需要将MyBall事件连接到pitcher.catches方法。由于在方法中声明了Myball,因此无法使用WithEvents关键字。

要在运行时连接处理程序,请使用AddHandler

Dim myBall As New Ball
Dim pitcher As New Pitcher
AddHandler myBall.BallInPlay, AddressOf pitcher.catches
myBall.OnBallInPlay(New BallEventArgs(10, 20))

要断开处理程序,请使用RemoveHandler

RemoveHandler myBall.BallInPlay, AddressOf pitcher.catches

编辑

我只是理解了问题/遗漏部分。您只需定义Pitcher.MySender,因为:

  • 使用WithEvents关键字
  • 进行声明
  • 您已通过catches

    调用Handles mySender.BallInPlay方法
    Dim myBall As New Ball
    Dim pitcher As New Pitcher
    pitcher.mySender = myBall
    myBall.OnBallInPlay(New BallEventArgs(10, 20))
    

答案 1 :(得分:1)

您定义pitcher,但从不使用它:

Dim pitcher As New Pitcher

没有做任何事情,因此,永远不会调用catches子程序,因为没有球的实例。

此外,mySender永远不会被实例化,而mySendermyBall会引用对Ball的不同引用

相关问题