Combining Delegates: Multicast Delegates

A delegate can hold a reference (that is, the address) to a method. It is possible to create delegates holding references to more than one method by creating multicast delegates. A multicast delegate is the combination of two or more delegates into a single delegate, providing the delegate the ability to make multiple invocations. The following code demonstrates how to create a multicast delegate, having two instances of the same delegate pointing to two different methods:

image

In this scenario you have two methods that behave differently, but both respect the delegate signature. A new delegate (CombinedDelegate) is created invoking the System.Delegate.Combine method that receives the series of delegates to be combined as arguments. It is worth mentioning that Combine returns a System.Delegate; therefore, an explicit conversion via CType is required with Option Strict On. With a single call to CombinedDelegate.Invoke, you can call both WriteSomething and WriteSomethingMoreComplex. The preceding code produces the following output:

Simply report your text: Test message
Today is 24/09/2009 and you wrote Test message

Delegate Keyword and System.Delegate

Delegate is a reserved keyword in Visual Basic. Because of this, to invoke the System.Delegate.Combine shared method the full name of the class has been utilized. You can still take advantage of the shortened syntax including Delegate within square brackets. In other words, you can write something like this: [Delegate].Combine(params()). This works because the System namespace is imported by default, and square parentheses make the compiler consider the enclosed word as the identifier of a class exposed by one of the imported namespaces, instead of a reserved keyword.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.231.128