Source code location: ./delegates/test.cs
using System; namespace Delegates { public class Test { public delegate int CalculationHandler (int x, int y); public static void Main (string[] args) { Math math = new Math(); CalculationHandler allTargets = null; CalculationHandler sumHandler = new CalculationHandler (math.Sum); CalculationHandler multiplyHandler = new CalculationHandler (math.Multiply); CalculationHandler substractionHandler = new CalculationHandler (math.Subtract); allTargets += sumHandler; allTargets += multiplyHandler; allTargets += substractionHandler; int result = allTargets (4, 3); Console.WriteLine ("Take 1."); Console.WriteLine ("Calculation result: " + result); // ------------------------------------------------------------------- // The result here is '1' because it is what the last delegate, // substractionHandler, returned. Basically, it overwrote the action // of the previous delegate(s) in the chain. This is, probably, not // what you expected. // ------------------------------------------------------------------- Console.WriteLine ("Take 2."); foreach (CalculationHandler calcHandler in allTargets.GetInvocationList()) { try { result = calcHandler (4, 3); Console.WriteLine ("Calculation result: " + result); } catch {} // We've ignored exceptions in this example to let other delegates do their work. // In a real-life scenario you might either let the exception propagate, or // consume it and handle it in a meaningful way. } } } public class Math { public int Sum (int x, int y) { return x + y; } public int Multiply (int x, int y) { return x * y; } public int Subtract (int x, int y) { return x - y; } } }
Copyright © 2004-2006, Milan Negovan. All rights reserved. | License
Back to AspNetResources.com