Partilhar via


Como: Passar Procedimentos para outro Procedimento em Visual Basic.

This example shows how to use delegates to pass a procedure to another procedure.

A delegate is a type that you can use like any other type in Visual Basic. The AddressOf operator returns a delegate object when applied to a procedure name.

This example has a procedure with a delegate parameter that can take a reference to another procedure, obtained with the AddressOf operator.

Create the delegate and matching procedures

  1. Create a delegate named MathOperator.

    Delegate Function MathOperator( 
        ByVal x As Double, 
        ByVal y As Double 
    ) As Double
    
  2. Create a procedure named AddNumbers with parameters and return value that match those of MathOperator, so that the signatures match.

    Function AddNumbers( 
        ByVal x As Double, 
        ByVal y As Double 
    ) As Double
        Return x + y
    End Function
    
  3. Create a procedure named SubtractNumbers with a signature that matches MathOperator.

    Function SubtractNumbers( 
        ByVal x As Double, 
        ByVal y As Double
    ) As Double
        Return x - y
    End Function
    
  4. Create a procedure named DelegateTest that takes a delegate as a parameter.

    This procedure can accept a reference to AddNumbers or SubtractNumbers, because their signatures match the MathOperator signature.

    Sub DelegateTest( 
        ByVal x As Double, 
        ByVal op As MathOperator, 
        ByVal y As Double 
    )
        Dim ret As Double
        ret = op.Invoke(x, y) ' Call the method.
        MsgBox(ret)
    End Sub
    
  5. Create a procedure named Test that calls DelegateTest once with the delegate for AddNumbers as a parameter, and again with the delegate for SubtractNumbers as a parameter.

    Protected Sub Test()
        DelegateTest(5, AddressOf AddNumbers, 3)
        DelegateTest(9, AddressOf SubtractNumbers, 3)
    End Sub
    

    Quando Test é chamado, ele primeiro exibe o resultado de AddNumbers atuando em 5 e 3, que é 8. Em seguida, o resultado de SubtractNumbers atuando em 9 e 3 for exibida, que é 6.

Consulte também

Tarefas

Como: Invocar um método delegate (Visual Basic)

Referência

Operador AddressOf (Visual Basic)

Instrução Delegate

Outros recursos

Delegados (Visual Basic)