MakeGenericType方法,运行时传入泛型T参数,动态生成泛型类

在某些应用情况下,泛型T并非在代码中写入,而需要根据不同的情况去动态填入,微软也提供了相应生成的方法:Type.MakeGenericType

 

方法传入Type参数来替代泛型类参数,话不多说上代码。先创建一个接口,定义print方法,在下面的实现方法中输出“T”的类型

   public interface ITest
    {
        void print();
    }

    public class Test<T> : ITest
    {
        public void print()
        {
            Console.WriteLine(typeof(T).Name);
        }
    }

在主函数中编写测试,依次测试如何创建泛型类,通过输出类型来判断

        public static void Main()
        {
            Type type = typeof(Test<>);
            ITest test;

            //Int32
            Type tInt32 = type.MakeGenericType(GetInt32());
            test = Activator.CreateInstance(tInt32) as ITest;
            test.print();

            //Int64
            Type tInt64 = type.MakeGenericType(GetInt64());
            test = Activator.CreateInstance(tInt64) as ITest;
            test.print();

            Type tString = type.MakeGenericType(GetString());
            test = Activator.CreateInstance(tString) as ITest;
            test.print();

            Console.Read();
        }

        static Type GetInt32()
        {
            return typeof(Int32);
        }

        static Type GetInt64()
        {
            return typeof(Int64);
        }

        static Type GetString()
        {
            return typeof(String);
        }

最终结果,等同于依次生成了tInt32(Test<Int32>),tInt64(Test<Int64>),tString(Test<String>),输出如下:

此功能可适用于很多类型未知但需要泛型的场合,例如ORM框架中的类型映射转换等等

原文地址:https://www.cnblogs.com/TuringLi/p/9213449.html