Um guia sobre DELEGATES (os ponteiros para função do VB.NET)
por Fernando da Cruz
at
27/07/2011 17:00
|
Permalink
DELEGATES - um recurso interessante.
Veja: http://www.codeproject.com/vb/net/Delegate.asp
O artigo acima explica sobre DELEGATES. Um recurso bem interessante. Permite não só criar um ponteiro seguro para métodos e funções, como servir para anexar várias funções em um único ponteiro de forma que você possa chamá-las todas de uma vez. Veja abaixo um exemplo compilado do artigo acima:
Public Delegate Sub GreetingDelegate(ByVal MsgString As String)
Public Sub GoodMoring(ByVal YourName As String)
Console.WriteLine("Good Morning " + YourName + " !")
End Sub
Public Sub GoodNight(ByVal YourName As String)
Console.WriteLine("Good Night " + YourName + " !")
End Sub
'Instanciando o DELEGATE (definido acima)
Dim MyGreeting As GreetingDelegate
'Here we assign the address of the function we wish to encapsulate
'to the delegate
Console.WriteLine("Adding 'GoodMoring' Reference To A Delegate...")
MyGreeting = AddressOf GoodMoring
' E finalmente:
'Invoking the delegate
Console.WriteLine("Invoking Delegate...")
MyGreeting.Invoke("Rogerio")
' ou...
MyGreeting("Rogerio")
' Combinando DELEGATES:
Dim MorningGreets As GreetingDelegate
Dim EveningGreets As GreetingDelegate
MorningGreets = AddressOf GoodMorning
EveningGreets = New GreetingDelegate(AddressOf GoodEvening)
Console.WriteLine("Adding 'MorningGreets' And" & _
" 'EveningGreets' References To A Delegate...")
Dim AllGreets As GreetingDelegate = _
[Delegate].Combine(MorningGreets, EveningGreets)
AllGreets("Rogerio")
