2019-10-14 【c#】反射:泛型反射:MakeGener

2019-10-14  本文已影响0人  持刀的要迟到了

https://www.cnblogs.com/OpenCoder/p/5957668.html

using System;
using System.Reflection;
using static RFTest.ReflectionTest;

namespace RFTest
{
    //类ReflectionTest中定义了一个泛型函数DisplayType和泛型类MyGenericClass
    class ReflectionTest
    {
        //泛型类MyGenericClass有个静态函数DisplayNestedType
        public class MyGenericClass<T>
        {
            public static void DisplayNestedType()
            {
                Console.WriteLine(typeof(T).ToString());
            }

            public void DisplayType()
            {
                Console.WriteLine(typeof(T).ToString());
            }
        }

        public void DisplayType<T>()
        {
            Console.WriteLine(typeof(T).ToString());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ReflectionTest rt = new ReflectionTest();

            //先获取到DisplayType<T>的MethodInfo反射对象
            MethodInfo mi = rt.GetType().GetMethod("DisplayType");

            //然后使用MethodInfo反射对象调用ReflectionTest类的DisplayType<T>方法,
            //这时要使用MethodInfo的MakeGenericMethod函数指定函数DisplayType<T>的泛型类型T
            mi.MakeGenericMethod(new Type[] { typeof(string) }).Invoke(rt, null);

            //这里获取MyGenericClass<T>的Type对象,注意GetNestedType方法的参数要用MyGenericClass`1这种格式才能获得MyGenericClass<T>的Type对象
            Type myGenericClassType = rt.GetType().GetNestedType("MyGenericClass`1");
            //然后用Type对象的MakeGenericType函数为泛型类MyGenericClass<T>指定泛型T的类型,比如上面我们就用MakeGenericType函数将MyGenericClass<T>指定为了MyGenericClass<float>,然后继续用反射调用MyGenericClass<T>的DisplayNestedType静态方法
            myGenericClassType.MakeGenericType(new Type[] { typeof(float) }).GetMethod("DisplayNestedType", BindingFlags.Static | BindingFlags.Public).Invoke(null, null);


            Type myGenericClassType2 = typeof(MyGenericClass<>);
            myGenericClassType2.MakeGenericType(typeof(double)).GetMethod("DisplayNestedType").Invoke(null, null);


            Type myGenericClassType3 = typeof(MyGenericClass<>);
            // 非静态方法,需要先创建实例调用
            //myGenericClassType2.MakeGenericType(typeof(double)).GetMethod("DisplayType").Invoke(null, null);
            Type geneTp = myGenericClassType3.MakeGenericType(typeof(int));
            MyGenericClass<int> obj = Activator.CreateInstance(geneTp) as MyGenericClass<int>;
            obj.DisplayType();
            object obj2 = Activator.CreateInstance(geneTp);
            MethodInfo mi2 = obj2.GetType().GetMethod("DisplayType");
            mi2.Invoke(obj2, null);


            Console.ReadLine();
        }
    }
}
image.png
上一篇 下一篇

猜你喜欢

热点阅读