VB.NET Language in a Nutshell

   
Delegate Statement

Syntax

[ AccessModifier ] Delegate Sub name [([ arglist ])]) [ AccessModifier ] Delegate Function name [([ arglist ])]) As type

AccessModifier (optional; Keyword)

Specifies scope/accessibility the same as when declaring a subroutine or function. Can be one of Public , Private , Protected , Friend , Protected Friend , or Shadows .

name (required; String literal)

The name of the delegate class.

arglist (optional)

The argument list; it has the same syntax as when defining a subroutine or function.

Description

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 .

Rules at a Glance

Example

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

   

Категории