Can you chain the result of one delegate to be the input of another in C#?

前端 未结 5 1108
春和景丽
春和景丽 2021-01-14 13:09

I am looking for a way to chain several delegates so the result from one becomes the input of the next. I am trying to use this in equation solving program where portions ar

5条回答
  •  盖世英雄少女心
    2021-01-14 14:08

    I have been working on a similar problem myself which involved invoking a sequence of delegates and passing the output of one delegate to the next (and so on...) so thought you might be interested to see the code I developed as a proof-of-concept:

    static class Program
    {
        private static IList> delegateList = 
            new List>()
        {
            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(this IEnumerable> source, 
                                                T startValue)
        {
            T result = startValue;
    
            foreach (Func function in source)
            {
                result = function(result);
            }
    
            return result;
        }
    }
    

    The sequence has to contain delegates of the same type so is not as powerful as the already accepted answer but with a few tweaks, both bits of code could be combined to provide a powerful solution.

提交回复
热议问题