共用方式為


如何:叫用委派方法 (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
    

另請參閱