Multicasting
At times it is desirable to multicast, or call two implementing methods through a single delegate. You accomplish multicasting by encapsulating the various methods in delegates. Then you combine the delegates using the Delegate.Combine( ) shared method. The Combine( ) method takes an array of delegates as a parameter and returns a new delegate that represents the combination of all the delegates in the array.
To see how this works, create a simplistic class that declares a delegate:
Public Class MyClassWithDelegate
' the delegate declaration
Public Delegate Sub StringDelegate(ByVal s As String)
End ClassThen create a class (MyImplementingClass) that implements a number of methods that match the StringDelegate:
Public Class MyImplementingClass
Public Shared Sub WriteString(ByVal s As String)
Console.WriteLine("Writing string {0}", s)
End Sub
Public Shared Sub LogString(ByVal s As String)
Console.WriteLine("Logging string {0}", s)
End Sub
Public Shared Sub TransmitString(ByVal s As String)
Console.WriteLine("Transmitting string {0}", s)
End Sub
End ClassWithin the Run( ) method of your Tester class, you’ll instantiate three StringDelegate objects (Writer, Logger, Transmitter):
Dim Writer, Logger, Transmitter As MyClassWithDelegate.StringDelegate
You instantiate these delegates by passing in the address of the methods you wish to encapsulate:
Writer = New MyClassWithDelegate.StringDelegate( _ AddressOf MyImplementingClass.WriteString) Logger = New MyClassWithDelegate.StringDelegate( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access