相关疑难解决方法(0)

如何使用反射找到特定的泛型过载?

我试图创建一个Expression将调用特定的泛型重载方法(Enumerable.Average在我的第一个测试用例中).特定类型绑定直到运行时才知道,因此我需要使用它Reflection来查找和创建正确的泛型方法(Expression从解析的文本创建).

所以如果我在运行时知道我想找到这个特定的重载:

public static double Average<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector)
Run Code Online (Sandbox Code Playgroud)

如何MethodInfo使用反射解决该特定问题?

到目前为止,我有以下选择声明:

MethodInfo GetMethod(Type argType, Type returnType)
{
    var methods = from method in typeof(Enumerable).GetMethods(BindingFlags.Public | BindingFlags.Static)
      where method.Name == "Average" &&
      method.ContainsGenericParameters &&                              
      method.GetParameters().Length == 2 &&
      // and some condition where method.GetParameters()[1] is a Func that returns type argType
      method.ReturnType == returnType
      select method;

      Debug.Assert(methods.Count() == 1);
      return methods.FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

上面将它缩小到三个重载,但我想反映并找到需要在Func<TSource, int>哪里的特定重载argType == typeof(int) …

c# generics reflection .net-3.5 linq-expressions

4
推荐指数
1
解决办法
2512
查看次数

标签 统计

.net-3.5 ×1

c# ×1

generics ×1

linq-expressions ×1

reflection ×1