请看下面的代码:
Public Delegate Sub TestButtonClick(ByVal test As Integer)
Public Class Person
Private Name As String
Private ID As Integer
Public Event ButtonClick As TestButtonClick
Public Sub DelegateTest1(ByVal Test As Integer)
MsgBox(Test)
End Sub
Public Sub ChangeName()
RaiseEvent ButtonClick(1)
End Sub
Public Sub DelegateTest2()
MsgBox("Delegate Test 2")
End Sub
Public Sub DelegateTest3()
MsgBox("Delegate Test 3")
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim p1 As Person = New Person
AddHandler p1.ButtonClick, AddressOf p1.DelegateTest1
AddHandler p1.ButtonClick, AddressOf p1.DelegateTest2
AddHandler p1.ButtonClick, AddressOf p1.DelegateTest3
p1.ChangeName()
End Sub
End Class
输出是:
1
DelegateTest2
DelegateTest3
我不明白为什么这个应用程序编译,即委托在其签名中接受一个整数,但Person.DelegateTest2
不Person.DelegateTest3
接受。
如果我将 Person.DelegateTest2() 更改为以下内容,那么我确实会收到一个错误,如我所料:
Public Sub DelegateTest2(ByVal Test As Integer, ByVal Test2 As Integer)
MsgBox("Delegate Test 2")
End Sub
为什么当它有参数时,代表允许你传递零个参数,即在我的例子中是一个整数?