Delegate Statement |
[ AccessModifier ] Delegate Sub name [([ arglist ])]) [ AccessModifier ] Delegate Function name [([ arglist ])]) As type
Specifies scope/accessibility the same as when declaring a subroutine or function. Can be one of Public , Private , Protected , Friend , Protected Friend , or Shadows .
The name of the delegate class.
The argument list; it has the same syntax as when defining a subroutine or function.
Declares the parameters and return type of a delegate class. Note that the syntax is the same as that used when declaring a subroutine or function, with the addition of the keyword Delegate .
Any procedure whose argument list and return type matches that of a declared delegate class can be used to create an instance of this delegate class, as the upcoming example illustrates.
For more information on delegates, see Section 7.1 in Chapter 7.
Consider the following method:
Public Class Class1 Public Sub AMethod(ByVal s As String) Msgbox(s) End Sub End Class
Consider the following delegate declaration:
Delegate Sub ADelegate(ByVal s As String)
The following code uses the delegate to call the AMethod of Class1:
Protected Sub Form1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Click ' Object of type Class1 Dim obj As New Class1( ) ' Declare a new delegate Dim delg As ADelegate ' Define the delegate, passing the address of the object's method delg = New ADelegate(AddressOf obj.AMethod) ' Call the method using the Invoke method of the delegate delg.Invoke("test") End Sub