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