动态函数列表并动态调用它们

我希望能够在List中存储各种静态方法,然后查找它们并动态调用它们。

每个静态方法都有不同数量的args,类型和返回值

static int X(int,int).... static string Y(int,int,string) 

我想要一个List,我可以将它们全部添加到:

 List list list.Add(X); list.Add(Y); 

然后:

 dynamic result = list[0](1,2); dynamic result2 = list[1](5,10,"hello") 

如何在C#4中做到这一点?

您可以使用适当的委托类型为每个方法创建委托实例列表。

 var list = new List { new Func (X), new Func (Y) }; dynamic result = list[0](1, 2); // like X(1, 2) dynamic result2 = list[1](5, 10, "hello") // like Y(5, 10, "hello") 

你实际上在这里不需要dynamic的力量,你可以用简单的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); } } 

(好吧,你需要一个演员,但你需要以某种方式知道每个存储方法的签名)

  List list = new List(); Action myFunc = (int x, int y) => Console.WriteLine("{0}, {1}", x, y); Action myFunc2 = (int x, int y) => Console.WriteLine("{0}, {1}", x, y); list.Add(myFunc); list.Add(myFunc2); (list[0])(5, 6);