I myself worked on a similar problem, which included calling a sequence of delegates and passing the output of one delegate to the next (etc.), so I thought you might be interested to see the code that I developed as a proof of concept:
static class Program { private static IList<Func<int, int>> delegateList = new List<Func<int, int>>() { AddOne, AddOne, AddOne, AddOne, AddOne, AddOne, AddOne, AddOne, AddOne, AddOne, }; static void Main(string[] args) { int number = 12; Console.WriteLine("Starting number: {0}", number); Console.WriteLine("Ending number: {0}", delegateList.InvokeChainDelegates(number)); Console.ReadLine(); } public static int AddOne(int num) { return num + 1; } public static T InvokeChainDelegates<T>(this IEnumerable<Func<T, T>> source, T startValue) { T result = startValue; foreach (Func<T, T> function in source) { result = function(result); } return result; } }
The sequence should contain delegates of the same type, so it is not as powerful as the already accepted answer, but with several settings, both bits of code can be combined to provide a powerful solution.
Benjamin Gale Nov 28 '12 at 20:24 2012-11-28 20:24
source share