我知道我的问题很简单,但我无法弄清楚我的代码出了什么问题。我有一本Head First C#书,我用 VB.NET 转换了代码。我预计在单击窗体中的按钮后将调用Pitcher
类的catches
子例程。但什么也没发生。
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
将倾听。是不是,还是我错过了一些明显而重要的东西?
您需要将 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
关键字声明
的 并且您已经通过
Handles mySender.BallInPlay
调用了catches
方法Dim myBall As New Ball Dim pitcher As New Pitcher pitcher.mySender = myBall myBall.OnBallInPlay(New BallEventArgs(10, 20))
你定义了pitcher
,但你从不使用它:
Dim pitcher As New Pitcher
不执行任何操作,因此,由于没有球的实例,因此永远无法调用接球子例程。
此外,mySender
永远不会实例化,mySender
和myBall
引用对Ball
的不同引用