
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Obtaining Return Values from Each Delegate in a Multicast Delegate
|
491
values returned by individual delegates in a multicast delegate are lost—all except
the value from the last delegate to fire, the return value of which is returned to the
calling application. You need to be able to access the return value of each delegate
that is fired in the multicast delegate.
Solution
Use the GetInvocationList method as in Recipe 9.1. This method returns each indi-
vidual delegate from a multicast delegate. In doing so, you can invoke each delegate
individually and get its return value. The following method creates a multicast dele-
gate called
All and then uses GetInvocationList to fire each delegate individually.
After firing each delegate, the return value is captured:
public static void TestIndividualInvokesRetVal( )
{
MyDelegate myDelegateInstance1 = new MyDelegate(TestInvoke.Method1);
MyDelegate myDelegateInstance2 = new MyDelegate(TestInvoke.Method2);
MyDelegate myDelegateInstance3 = new MyDelegate(TestInvoke.Method3);
MyDelegate allInstances =
myDelegateInstance1 +
myDelegateInstance2 +
myDelegateInstance3;
Console.WriteLine("Invoke individually (Obtain each return value):");
foreach (MyDelegate instance in allInstances.GetInvocationList( ))
{
int retVal = instance( );
Console.WriteLine("\tOutput: ...