如果你只做能力范围之内的事,你就永远不会有进步!|

陈侠云

园龄:2年10个月粉丝:1关注:1

观《深入理解C#》有感---泛型的反射应用

泛型的完整类型名称

完整名称+`+参数数量+[ 参数类型 + ],例如:

        static void Main(string[] args)
        {
            Console.WriteLine(typeof(List<>));                  // -> System.Collections.Generic.List`1[T]
            Console.WriteLine(typeof(List<int>));               // -> System.Collections.Generic.List`1[System.Int32]
            Console.WriteLine(typeof(Dictionary<,>));           // -> System.Collections.Generic.Dictionary`2[TKey,TValue]
            Console.WriteLine(typeof(Dictionary<int,float>));   // -> System.Collections.Generic.Dictionary`2[System.Int32,System.Single]
        }

泛型重要的方法

GetGenericTypeDefinition

作用于已构造的类型,获取它的泛型类型定义

MakeGenericType

作用于泛型类型定义,返回一个已构造类型

        static void Main(string[] args)
        {
            Type closedByTypeof = typeof(List<string>);

            Type closedByName = Type.GetType("System.Collections.Generic.List`1[System.String]");
            
            Type defByName = Type.GetType("System.Collections.Generic.List`1");
            Type closedByMethod = defByName.MakeGenericType(typeof(string));

            Console.WriteLine(closedByTypeof == closedByName);
            Console.WriteLine(closedByTypeof == closedByMethod);

            // ------------------------

            Type defByMehod = closedByTypeof.GetGenericTypeDefinition();

            Console.WriteLine(defByMehod == defByName);
        }

三次输出都返回true

反射泛型方法

        public static void PrintType<T>()
        {
            Console.WriteLine(typeof(T).Name);
        }

        static void Main(string[] args)
        {
            Type type = typeof(Program);
            MethodInfo definition = type.GetMethod("PrintType");
            MethodInfo constructed = definition.MakeGenericMethod(typeof(string));
            constructed.Invoke(null, null);
        }

本文作者:陈侠云

本文链接:https://www.cnblogs.com/chenxiayun/p/18296533

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   陈侠云  阅读(4)  评论(0编辑  收藏  举报
//雪花飘落效果
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起