日期:2014-05-17  浏览次数:20718 次

请教:关于反射+泛型+重载的问题
最近在研究C#的反射,发现功能很强大,但是碰到了个问题百思不得其解。比如说一个类中有这样两个函数:
C# code

    public class Test
    {
        public static void A<T>(T a)
        {
            Console.WriteLine("A1");
        }

        public static void A<T>(T a, T b)
        {
            Console.WriteLine("A2");
        }
    }


  那么我该如何利用Type.GetMethod来获取其中指定的一个函数呢?似乎只能通过Type.GetMethod(String, Type[])这个重载来获取,那么,我必须将我的方法体的参数类型{T}或者{T,T}传递进去,可是既然T为泛型,无法找到一个确定的Type可以表示,这样问题就卡在这里了。
  希望有高手可以为我指点一下思路,或者大家一起帮忙思考一下,谢谢!
   
  如果上面的问题有解,那么我或许可以继续下面的问题:
C# code

public static IQueryable<TResult> Select<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, int, TResult>> selector);
public static IQueryable<TResult> Select<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector);



------解决方案--------------------
可以获得所有Method,然后找到你要的,通过 MakeGenericMethod来触发,如下网上的例子

MethodInfo myMethod = myString.GetType().GetMethods().First(m => m.Name.Equals("A") && m.IsGenericMethod);
myMethod.MakeGenericMethod(typeof(int)).Invoke(myString, new object[] { 100 });
------解决方案--------------------
用GetMethods方法返回所有的方法,然后用Linq过滤,结合MethodInfo的属性,举例如下:
C# code
Type[] generictypes = null;
ParameterInfo[] pinfos = null;
MethodInfo ms = typeof(Test).GetMethods().First((p) => p.IsGenericMethod && p.Name == "A"
    && (generictypes = p.GetGenericArguments()).Length == 1 && generictypes[0].Name == "T"
    && (pinfos = p.GetParameters()).Length == 2 && pinfos[0].ParameterType == generictypes[0] && pinfos[1].ParameterType == generictypes[0]);