a list of dynamic functions and dynamically calling them

前端 未结 3 1164
长发绾君心
长发绾君心 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 21:13

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

    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 l = new List();
            l.Add((Func)f);
            l.Add((Action)g);
            int r = ((Func)l[0])(5);
            ((Action)l[1])(0, 0);
        }
    }
    
    
    

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

    提交回复
    热议问题