如何:调用委托方法 (Visual Basic)

此示例演示如何将方法与委托关联然后通过委托调用该方法。

创建委托和匹配过程

  1. 创建一个名为 MySubDelegate 的委托。

        Delegate Sub MySubDelegate(ByVal x As Integer)
    
  2. 声明一个类,该类包含与该委托具有相同签名的方法。

        Class class1
            Sub Sub1(ByVal x As Integer)
                MsgBox("The value of x is: " & CStr(x))
            End Sub
        End Class
    
  3. 定义一个方法,该方法创建该委托的实例并通过调用内置的 Invoke 方法调用与该委托关联的方法。

        Protected Sub DelegateTest()
            Dim c1 As New class1
            ' Create an instance of the delegate.
            Dim msd As MySubDelegate = AddressOf c1.Sub1
            ' Call the method.
            msd.Invoke(10)
        End Sub
    

请参见

参考

Delegate 语句

概念

多线程应用程序(C# 和 Visual Basic)

其他资源

委托 (Visual Basic)

事件 (Visual Basic)