2008-11-28 78 views
1

我试图得到该方法的MethodInfo对象:如何获得一般方法的MethodInfo?

Any<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) 

我有工作了你如何指定Func<TSource, Boolean>位类型参数的问题......

MethodInfo method = typeof(Enumerable).GetMethod("Any", new[] { typeof(Func<what goes here?, Boolean>) }); 

帮助赞赏。

+0

可能重复http://stackoverflow.com /问题/ 269578/GET-A-仿制方法,而无需-使用-的getMethods) – nawfal 2013-10-08 10:58:47

回答

2

无法在一次调用中获得它,因为您需要制作一个泛型类型,该类型由方法的通用参数(本例中为TSource)构造而成。并且,由于它特定于该方法,您需要获取该方法并构建通用Func类型。鸡和鸡蛋问题?

你可以做的是获得Enumerable上定义的所有Any方法,然后遍历这些方法来获得你想要的。

3

您可以创建一个扩展方法来完成检索所有方法并筛选它们以便返回所需的泛型方法的工作。

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<,>) }); 
的[获取泛型方法不使用的getMethods(
相关问题