MethodInfo GetBaseDefinition()方法不使用通用基类型

时间:2016-03-11 15:09:46

标签: c# reflection

class Program
{
    class Example : List<Type> { }

    static void Main(string[] args)
    {
        var mi = typeof(Example).GetMethod("IndexOf", new Type[] { typeof(Type), typeof(int) });
        var realMi = MyFunction(mi);
        Console.WriteLine(string.Format("Initial definition: {0}", mi));
        Console.WriteLine(string.Format("Base definition: {0}", mi.GetBaseDefinition()));
        Console.WriteLine(string.Format("MyFunction Result: {0}", realMi));

        var tType1 = typeof(List<>).GetGenericTypeDefinition().GetGenericArguments()[0];
        Console.WriteLine(string.Format("Goal Example 1: {0}",
            typeof(List<>).GetMethod("IndexOf", new Type[] { tType1, typeof(int) })));

        var tType2 = mi.DeclaringType.GetGenericTypeDefinition().GetGenericArguments()[0];
        Console.WriteLine(string.Format("Goal Example 2: {0}",
            mi.DeclaringType.GetGenericTypeDefinition().GetMethod("IndexOf",
                new Type[] { tType2, typeof(int) })));
        Console.ReadKey();
    }

    static MethodInfo MyFunction(MethodInfo mi)
    {
        // what code should be there???            
        return mi.DeclaringType.GetGenericTypeDefinition().GetMethod("IndexOf",
            mi.GetParameters().Select(p => p.GetType()).ToArray());
    }
}

如何从MyFunction获取目标?

控制台输出:

Initial definition: Int32 IndexOf(System.Type, Int32)
Base definition: Int32 IndexOf(System.Type, Int32)
MyFunction Result:
Goal Example 1: Int32 IndexOf(T, Int32)
Goal Example 2: Int32 IndexOf(T, Int32)

1 个答案:

答案 0 :(得分:1)

尝试:

static MethodInfo MyFunction(MethodInfo mi) {
    Type listT = mi.DeclaringType.GetGenericTypeDefinition();
    MethodInfo miListT = (MethodInfo)MethodBase.GetMethodFromHandle(mi.MethodHandle, listT.TypeHandle);
    return miListT;
}

你可以使用相同的&#34;技巧&#34;来自List<X1>.IndexOfList<Y1>.IndexOfList<>.IndexOfList<X1>.IndexOfList<X1>.IndexOfList<>.IndexOf