
114
|
Chapter 8: Delegates and Events
This is the Title of the Book, eMatter Edition
Copyright © 2006 O’Reilly & Associates, Inc. All rights reserved.
Using a Delegate to Call a Method
To call a method using a delegate, use the Invoke method of the delegate. To illus-
trate, consider a class module with a simple method.
Public Class SimpleClass
Public Sub CallMe(ByVal content As String)
MsgBox(content)
End Sub
End Class
Delegates are one of the many .NET types. Visual Basic includes a Delegate
keyword that defines delegates. Since the goal is to call the CallMe method
through a delegate, that delegate must have the same signature as the called
method. This small example invokes the delegate from a click on a form, so the
delegate’s definition appears in the form’s class code.
Delegate Sub MyDelegate(ByVal s As String)
Finally, in the form’s Click event handler (which works via delegates, but don’t
think about that now), the call to
CallMe is made indirectly through a delegate.
Private Sub Form1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Click
' ----- Get an instance of the destination class.
Dim destClass As New SimpleClass( )
Dim theDelegate As MyDelegate
' ----- Connect the delegate to its target, the CallMe method.
theDelegate = New MyDelegate(AddressOf destClass.CallMe)
' ----- Make the call.
theDelegate.Invoke("Display this!")
End Sub
It doesn’t seem