我知道我的问题很简单,但我无法弄清楚我的代码有什么问题。我有这个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
将会收听。不是吗,还是我错过了一些明显而重要的东西?
答案 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
永远不会被实例化,而mySender
和myBall
会引用对Ball
的不同引用