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

fre*_*ith 20 .net c# dynamic c#-4.0

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

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

static int X(int,int)....
static string Y(int,int,string) 
Run Code Online (Sandbox Code Playgroud)

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

List<dynamic> list

list.Add(X);
list.Add(Y);
Run Code Online (Sandbox Code Playgroud)

然后:

dynamic result = list[0](1,2);
dynamic result2 = list[1](5,10,"hello")
Run Code Online (Sandbox Code Playgroud)

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

Ani*_*Ani 20

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

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")
Run Code Online (Sandbox Code Playgroud)