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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值