How to store delegates in a List

后端 未结 4 1165
灰色年华
灰色年华 2020-12-11 01:19

How can I store delegates (named, anonymous, lambda) in a generic list? Basically I am trying to build a delegate dictionary from where I can access a stored delegate using

相关标签:
4条回答
  • 2020-12-11 01:43

    Does System.Collections.Generic.Dictionary<string, System.Delegate> not suffice?

    0 讨论(0)
  • 2020-12-11 02:04
        public delegate void DoSomething();
    
        static void Main(string[] args)
        {
            List<DoSomething> lstOfDelegate = new List<DoSomething>();
            int iCnt = 0;
            while (iCnt < 10)
            {
                lstOfDelegate.Add(delegate { Console.WriteLine(iCnt); });
                iCnt++;
            }
    
            foreach (var item in lstOfDelegate)
            {
                item.Invoke();
            }
            Console.ReadLine();
        }
    
    0 讨论(0)
  • 2020-12-11 02:05
            Dictionary<string, Func<int, int>> fnDict = new Dictionary<string, Func<int, int>>();
            Func<int, int> fn = (a) => a + 1;
            fnDict.Add("1", fn);
            var re = fnDict["1"](5);
    
    0 讨论(0)
  • 2020-12-11 02:08

    Well, here's a simple example:

    class Program
    {
        public delegate double MethodDelegate( double a );
    
        static void Main()
        {
            var delList = new List<MethodDelegate> {Foo, FooBar};
    
    
            Console.WriteLine(delList[0](12.34));
            Console.WriteLine(delList[1](16.34));
    
            Console.ReadLine();
        }
    
        private static double Foo(double a)
        {
            return Math.Round(a);
        }
    
        private static double FooBar(double a)
        {
            return Math.Round(a);
        }
    }
    
    0 讨论(0)
提交回复
热议问题