一个动态函数列表并动态调用它们 [英] a list of dynamic functions and dynamically calling them

查看:98
本文介绍了一个动态函数列表并动态调用它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

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

我想有一个列表,我可以添加所有到:

 列表<动态>列表

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< dynamic> 
{
new Func< int,int,int> (X),
new Func< int,int,string,string> (Y)
};

动态结果=列表[0](1,2); // like X(1,2)
dynamic result2 = list [1](5,10,hello)// like Y(5,10,hello)


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 args, types and return values

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

I'd like to have a List that I can add them all to:

List<dynamic> list

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

and later:

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

How to do this in C# 4?

解决方案

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")

这篇关于一个动态函数列表并动态调用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆