Porady: wywoływanie metody delegata (Visual Basic)

W tym przykładzie pokazano, jak skojarzyć metodę z pełnomocnikiem, a następnie wywołać tę metodę za pośrednictwem delegata.

Tworzenie procedur delegata i dopasowywania

  1. Utwórz delegata o nazwie MySubDelegate.

    Delegate Sub MySubDelegate(ByVal x As Integer)
    
  2. Zadeklaruj klasę zawierającą metodę z tym samym podpisem co delegat.

    Class class1
        Sub Sub1(ByVal x As Integer)
            MsgBox("The value of x is: " & CStr(x))
        End Sub
    End Class
    
  3. Zdefiniuj metodę, która tworzy wystąpienie delegata i wywołuje metodę skojarzona z pełnomocnikiem, wywołując wbudowaną Invoke metodę.

    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
    

Zobacz też