请查看以下代码:
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
为什么委托允许你在有参数时传递零参数,即在我的情况下是一个整数?
答案 0 :(得分:2)
不要忘记VB.NET继承了来自心爱的VB的所有传统包袱。您可以通过将以下内容放在文件的顶部来使其严格,以使其表现为真正的.NET编程语言而不是混合废话:
Option Strict On
我还建议您将其设为default option
,这样就不会发现自己身处旷野。