我正在尝试创建一个Expression
这将调用特定的通用重载方法(Enumerable.Average
在我的第一个测试用例中)。然而,具体的类型绑定直到运行时才知道,所以我需要使用Reflection
找到并创建正确的通用方法(Expression
是从解析的文本创建的)。
因此,如果我在运行时知道我想要找到这个特定的重载:
public static double Average<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector)
我该如何解决这个特定问题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();
}
上面将其范围缩小到三个重载,但我想反思并找到需要Func<TSource, int>
where argType == typeof(int)
.
我很困惑,感谢任何帮助。
你需要使用MethodInfo.MakeGenericMethod罢工>
编辑:好的,我误解了这个问题......这个方法应该做你想做的事:
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)