如何我找到具体的泛型重载使用反射? [英] How to I find specific generic overload using reflection?

查看:183
本文介绍了如何我找到具体的泛型重载使用反射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个防爆pression 将调用特定的通用重载的方法(Enumerable.Average C>在我的第一个测试用例)。具体类型绑定不知道,直到运行时不过,所以我需要使用反射查找和创建正确的泛型方法(防爆pression 正在从分析的文本创建)。

I am attempting to create an Expression that will invoke a specific generic overloaded method (Enumerable.Average in my first test case). The specific type bindings are not known until runtime however so I need to use Reflection to find and create the correct generic method (the Expression is being created from parsed text).

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

So if I know at runtime that I want to find this specific overload:

public static double Average<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector)

我如何解决特定的MethodInfo 使用反射?

到目前为止,我有以下选择语句:

So far I have the following selection statement:

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

以上范围缩小到三个重载,但我想反映,并找到具体的重载需要一个 Func键&LT; TSource,INT&GT; ,其中参数类型== typeof运算(INT)

我难倒和任何帮助是AP preciated。

I am stumped and any help is appreciated.

推荐答案

<打击>您需要使用的 MethodInfo.MakeGenericMethod

编辑:好的,我误解了问题......这个方法应该做你想要的:

OK, I had misunderstood the problem... This method should do what you want :

MethodInfo GetMethod(Type argType, Type returnType)
{
    var enumerableType = typeof(IEnumerable<>).MakeGenericType(new Type[] { argType });
    Console.WriteLine(enumerableType);
    var methods = from method in typeof(Enumerable).GetMethods(BindingFlags.Public | BindingFlags.Static)
      let parameters = method.GetParameters()
      let genParams = method.GetGenericArguments()
      where method.Name == "Average" &&
      method.ContainsGenericParameters &&                              
      parameters.Length == 2 &&
      parameters[1].ParameterType.GetGenericTypeDefinition() == typeof(Func<,>) &&
      parameters[1].ParameterType.GetGenericArguments()[1] == argType &&
      method.ReturnType == returnType
      select method;

      return methods.FirstOrDefault();
}

这篇关于如何我找到具体的泛型重载使用反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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