Delegados (Visual Basic)
Representantes são objetos que se referem aos métodos. They are sometimes described as type-safe function pointers because they are similar to function pointers used in other programming languages. But unlike function pointers, Visual Basic delegates are a reference type based on the class System.Delegate. Delegates can reference both shared methods — methods that can be called without a specific instance of a class — and instance methods.
Delegates and Events
Delegates are useful in situations where you need an intermediary between a calling procedure and the procedure being called. For example, you might want an object that raises events to be able to call different event handlers under different circumstances. Infelizmente, o objeto disparar os eventos não podem saber com antecedência qual manipulador de evento está lidando com um determinado evento. Visual Basicpermite que você os manipuladores de evento de associar dinamicamente com eventos, criando um delegado para você quando você usa o AddHandler demonstrativo. At run time, the delegate forwards calls to the appropriate event handler.
Although you can create your own delegates, in most cases Visual Basic creates the delegate and takes care of the details for you. For example, an Event statement implicitly defines a delegate class named <EventName>EventHandler as a nested class of the class containing the Event statement, and with the same signature as the event. O AddressOfdedemonstrativo implicitamente cria uma instância de um delegado que se refere a um determinado procedimento. As duas linhas de código a seguir são equivalentes. Na primeira linha, você vê a criação explícita de uma instância de Eventhandler, com uma referência para o método Button1_Click enviados como o argumento. A segunda linha é uma maneira mais conveniente de fazer a mesma coisa.
AddHandler Button1.Click, New EventHandler(AddressOf Button1_Click)
' The following line of code is shorthand for the previous line.
AddHandler Button1.Click, AddressOf Me.Button1_Click
You can use the shorthand way of creating delegates anywhere the compiler can determine the delegate's type by the context.
Declaring Events that Use an Existing Delegate Type
In some situations, you may want to declare an event to use an existing delegate type as its underlying delegate. The following syntax demonstrates how:
Delegate Sub DelegateType()
Event AnEvent As DelegateType
This is useful when you want to route multiple events to the same handler.
Delegate Variables and Parameters
Você pode usar delegados para outros, não-evento relacionados a tarefas, como segmentação livre ou com procedimentos precisarão chamar as versões diferentes de funções em tempo de execução.
For example, suppose you have a classified-ad application that includes a list box with the names of cars. The ads are sorted by title, which is normally the make of the car. A problem you may face occurs when some cars include the year of the car before the make. The problem is that the built-in sort functionality of the list box sorts only by character codes; it places all the ads starting with dates first, followed by the ads starting with the make.
To fix this, you can create a sort procedure in a class that uses the standard alphabetic sort on most list boxes, but is able to switch at run time to the custom sort procedure for car ads. To do this, you pass the custom sort procedure to the sort class at run time, using delegates.
AddressOf e expressões Lambda
Each delegate class defines a constructor that is passed the specification of an object method. An argument to a delegate constructor must be a reference to a method, or a lambda expression.
To specify a reference to a method, use the following syntax:
AddressOf [expression.]methodName
The compile-time type of the expression must be the name of a class or an interface that contains a method of the specified name whose signature matches the signature of the delegate class. The methodName can be either a shared method or an instance method. The methodName is not optional, even if you create a delegate for the default method of the class.
To specify a lambda expression, use the following syntax:
Function([parm As type, parm2 As type2, ...]) expression
O exemplo a seguir mostra que ambos AddressOf e expressões lambda é usado para especificar a referência para um representante.
Module Module1
Sub Main()
' Create an instance of InOrderClass and assign values to the properties.
' InOrderClass method ShowInOrder displays the numbers in ascending
' or descending order, depending on the comparison method you specify.
Dim inOrder As New InOrderClass
inOrder.Num1 = 5
inOrder.Num2 = 4
' Use AddressOf to send a reference to the comparison function you want
' to use.
inOrder.ShowInOrder(AddressOf GreaterThan)
inOrder.ShowInOrder(AddressOf LessThan)
' Use lambda expressions to do the same thing.
inOrder.ShowInOrder(Function(m, n) m > n)
inOrder.ShowInOrder(Function(m, n) m < n)
End Sub
Function GreaterThan(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean
Return num1 > num2
End Function
Function LessThan(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean
Return num1 < num2
End Function
Class InOrderClass
' Define the delegate function for the comparisons.
Delegate Function CompareNumbers(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean
' Display properties in ascending or descending order.
Sub ShowInOrder(ByVal compare As CompareNumbers)
If compare(_num1, _num2) Then
Console.WriteLine(_num1 & " " & _num2)
Else
Console.WriteLine(_num2 & " " & _num1)
End If
End Sub
Private _num1 As Integer
Property Num1() As Integer
Get
Return _num1
End Get
Set(ByVal value As Integer)
_num1 = value
End Set
End Property
Private _num2 As Integer
Property Num2() As Integer
Get
Return _num2
End Get
Set(ByVal value As Integer)
_num2 = value
End Set
End Property
End Class
End Module
The signature of the function must match that of the delegate type. For more information about lambda expressions, see Expressões Lambda (Visual Basic). Para obter mais exemplos de expressão lambda e AddressOf as atribuições de delegados, consulte Conversão de delegado reduzida (Visual Basic).
Related Topics
Title |
Description |
---|---|
Fornece um exemplo que mostra como associar um método com um delegado e depois chama esse método por meio do delegado. |
|
Como: Passar Procedimentos para outro Procedimento em Visual Basic. |
Demonstrates how to use delegates to pass one procedure to another procedure. |
Descreve como você pode atribuir funções e sub-rotinas delegados ou manipuladores mesmo quando suas assinaturas não são idênticas |
|
Fornece uma visão geral de eventos em Visual Basic. |