a list of dynamic functions and dynamically calling them

前端 未结 3 1135
长发绾君心
长发绾君心 2021-02-18 20:45

I would like to be able to store various static methods in a List and later look them up and dynamically call them.

Each of the static methods has different numbers of a

相关标签:
3条回答
  • 2021-02-18 20:55

    You can create a list of delegate-instances, using an appropriate delegate-type for each method.

    var list = new List<dynamic>
              {
                   new Func<int, int, int> (X),
                   new Func<int, int, string, string> (Y)
              };
    
    dynamic result = list[0](1, 2); // like X(1, 2)
    dynamic result2 = list[1](5, 10, "hello") // like Y(5, 10, "hello")
    
    0 讨论(0)
  • 2021-02-18 20:57
        List<dynamic> list = new List<dynamic>();
            Action<int, int> myFunc = (int x, int y) => Console.WriteLine("{0}, {1}", x, y);
            Action<int, int> myFunc2 = (int x, int y) => Console.WriteLine("{0}, {1}", x, y);
            list.Add(myFunc);
            list.Add(myFunc2);
    
            (list[0])(5, 6);
    
    0 讨论(0)
  • 2021-02-18 21:13

    You actually don't need the power of dynamic here, you can do with simple List<object>:

    class Program
    {
        static int f(int x) { return x + 1; }
        static void g(int x, int y) { Console.WriteLine("hallo"); }
        static void Main(string[] args)
        {
            List<object> l = new List<object>();
            l.Add((Func<int, int>)f);
            l.Add((Action<int, int>)g);
            int r = ((Func<int, int>)l[0])(5);
            ((Action<int, int>)l[1])(0, 0);
        }
    }
    

    (well, you need a cast, but you need to somehow know the signature of each of the stored methods anyway)

    0 讨论(0)
提交回复
热议问题