【问题标题】:a list of dynamic functions and dynamically calling them动态函数列表并动态调用它们
【发布时间】:2011-12-30 10:42:04
【问题描述】:

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

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

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

我想要一个可以将它们全部添加到的列表:

List<dynamic> list

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

及以后:

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

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

【问题讨论】:

  • +1,不同类型的问题。
  • 您正在寻找的是command pattern。谷歌,连同c#,你应该设置。

标签: c# .net c#-4.0 dynamic


【解决方案1】:
    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);

【讨论】:

    【解决方案2】:

    这里其实不需要dynamic的力量,用简单的List&lt;object&gt;就可以了:

    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);
        }
    }
    

    (嗯,你需要一个演员,但无论如何你需要知道每个存储方法的签名)

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2019-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-04
        相关资源
        最近更新 更多