我正在尝试创建一个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>
其中argType == typeof(int)
。
我难住,任何帮助表示赞赏。
有萨姆藏红花相关答案在这里:http://stackoverflow.com/questions/1452261/how-do-i-invoke-an -extension-方法-使用反射/。问题是关于扩展方法,但答案仍然与您的问题相关,因为所讨论的扩展方法(System.Enumerable.Where)与您的方法类似,是一种重载泛型方法。 – Joren 2009-09-23 12:50:09