动态调用列表上的方法

时间:2014-07-14 14:18:12

标签: c# linq dynamic reflection

我需要在元素列表中找到最大值或最小值{2,3,4}

 double[] doubleList = { 2, 3, 4 };
 doubleList.Max(); // return 4

如何动态调用正确的方法?

我可以为链接
中所述的两个元素实现此功能    http://tutorials.csharp-online.net/Attributes_and_Reflection%E2%80%94Late_Binding

编辑: 像这样:

 string methodName = "Min";
  var t = Type.GetType("System.Math");
  MethodInfo genericFunction = t.GetMethod(methodName, types);
  object val = genericFunction.Invoke(t, params);

1 个答案:

答案 0 :(得分:1)

好像你正在寻找Enumerable的Min函数而不是Math

double[] doubleList = { 2, 3, 4 };

string methodName = "Min";

var t = typeof(Enumerable);
MethodInfo method = t.GetMethods(BindingFlags.Static | BindingFlags.Public)
                 .Where(m => m.Name == methodName && m.ReturnType == typeof(double))
                 .FirstOrDefault();

object val = method.Invoke(t, new object[]{ doubleList });