【问题标题】:How to get MethodInfo of a generic method?如何获取泛型方法的 MethodInfo?
【发布时间】:2008-11-28 16:12:44
【问题描述】:
我正在尝试为该方法获取 MethodInfo 对象:
Any<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)
我遇到的问题是如何为Func<TSource, Boolean> 位指定类型参数...
MethodInfo method = typeof(Enumerable).GetMethod("Any", new[] { typeof(Func<what goes here?, Boolean>) });
帮助表示赞赏。
【问题讨论】:
标签:
c#
.net
reflection
extension-methods
【解决方案1】:
您可以创建一个扩展方法来完成检索所有方法并过滤它们以返回所需的通用方法的工作。
public static class TypeExtensions
{
private class SimpleTypeComparer : IEqualityComparer<Type>
{
public bool Equals(Type x, Type y)
{
return x.Assembly == y.Assembly &&
x.Namespace == y.Namespace &&
x.Name == y.Name;
}
public int GetHashCode(Type obj)
{
throw new NotImplementedException();
}
}
public static MethodInfo GetGenericMethod(this Type type, string name, Type[] parameterTypes)
{
var methods = type.GetMethods();
foreach (var method in methods.Where(m => m.Name == name))
{
var methodParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray();
if (methodParameterTypes.SequenceEqual(parameterTypes, new SimpleTypeComparer()))
{
return method;
}
}
return null;
}
}
使用上面的扩展方法,您可以编写类似于您预期的代码:
MethodInfo method = typeof(Enumerable).GetGenericMethod("Any", new[] { typeof(IEnumerable<>), typeof(Func<,>) });
【解决方案2】:
没有办法在一次调用中获得它,因为您需要创建一个由方法的泛型参数(在本例中为 TSource)构造的泛型类型。由于它特定于方法,因此您需要获取方法来获取它并构建通用 Func 类型。鸡和蛋的问题呵呵?
您可以做的是获取所有在 Enumerable 上定义的 Any 方法,然后遍历这些方法以获得您想要的。