观《深入理解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 中国大陆许可协议进行许可。
合集:
《深入理解C#》读书笔记
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步