C# Source Code: Obtaining individual return values from a chain of Delegates
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Obtaining individual return values from a chain of Delegates
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Wednesday, April 07, 2004
Hits:
551
Category:
Delegates/Events
Article:
The code below demonstrates two different ways of linking together delegates and calling them. The first method dynamically invokes each delegate invidually and thus receives each return value. The second call invokes the whole chain and hence only receives the final return value. using System; namespace vbUsers.Delegates { class DelegateCallBackDemo { public delegate int delAdd(int First, int Second); [STAThread] static void Main(string[] args) { //Declare new delegate delAdd delAddTest; //Chain link three instances of the delegate together and point each one //at the static Add method in the Callback class delAddTest = new delAdd(DelegateCallBack.Add); delAddTest += new delAdd(DelegateCallBack.Add); delAddTest += new delAdd(DelegateCallBack.Add); //Declare the parameters object[] oParams = new object[2]; int RunningTotal = 0; //Initialise the delegate parameters oParams[0] = 1; oParams[1] = 2; //Extract the Invocation list Delegate[] operators = delAddTest.GetInvocationList(); //Now invoke the delegates dynamically so that you can pass the result into the next delegate foreach(Delegate del in operators) { //Note, you do NOT get type checking when calling dynamically, so you should wrap these calls in a Try, Catch statement. RunningTotal += (int)del.DynamicInvoke(oParams); Console.WriteLine("Running Total: {0}",RunningTotal); } //Note alternative method of calling, but you will lose the return values from the //chain of delegates and instead only receive the final value. RunningTotal = 0; RunningTotal = delAddTest(1,2); Console.WriteLine("Total (when called directly): {0}",RunningTotal); //Pause to show results System.Threading.Thread.Sleep(1000); } } //Callback class for delegate class DelegateCallBack { static public int Add(int First, int Second) { int res = First + Second; Console.WriteLine("{0} + {1} = {2}",First,Second,res); return res; } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet