vendredi 11 mars 2016

MethodInfo GetBaseDefinition() method not working with generic base types

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());
    }
}

How to get the Goal from MyFunction?





Aucun commentaire:

Enregistrer un commentaire