观《深入理解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);
        }
posted @ 2024-07-11 16:43  陈侠云  阅读(11)  评论(0)    收藏  举报
//雪花飘落效果