调用Type.GetType获取SortedDictionary类型返回null的原因及解决方法
为什么
SortedDictionary用Type.GetType获取不到,而Dictionary可以? 这个问题我之前排查过,其实根源就在于两个类型所在的程序集不同!
问题原因
在.NET生态里:
Dictionary<TKey,TValue>属于核心程序集(.NET Framework里是mscorlib.dll,.NET Core/.NET 5+里是System.Private.CoreLib.dll),Type.GetType(string)方法默认会自动搜索当前调用程序集和这些核心程序集,所以直接写类型全名就能成功获取类型。- 但
SortedDictionary<TKey,TValue>不在核心程序集里:.NET Framework中它在System.dll,.NET Core/.NET 5+中则在System.Collections.dll。Type.GetType(string)默认不会搜索这些非核心程序集,所以只传类型全名会返回null。
解决方法
方案一:使用程序集限定名调用GetType
这是最稳妥的方式,你需要在类型全名后面追加程序集的标识信息。
比如在.NET Framework下可以这样写:
Type sortedDictType = Type.GetType("System.Collections.Generic.SortedDictionary`2[System.String,System.String], System");
如果担心版本或公钥冲突,建议先通过typeof获取准确的程序集限定名,再用这个字符串调用GetType:
// 先获取当前运行环境下的准确限定名 string qualifiedName = typeof(SortedDictionary<string, string>).AssemblyQualifiedName; // 再用这个字符串获取类型 Type sortedDictType = Type.GetType(qualifiedName);
这种方式适配所有.NET版本,因为typeof会自动读取当前环境的正确程序集信息。
方案二:先加载目标程序集再获取类型
如果你明确知道类型所在的程序集名称,可以先加载程序集,再从程序集中查找类型:
// .NET Framework环境下加载System.dll Assembly systemAssembly = Assembly.Load("System"); Type sortedDictType = systemAssembly.GetType("System.Collections.Generic.SortedDictionary`2[System.String,System.String]"); // .NET Core/.NET 5+环境下加载System.Collections.dll Assembly collectionsAssembly = Assembly.Load("System.Collections"); Type sortedDictType = collectionsAssembly.GetType("System.Collections.Generic.SortedDictionary`2[System.String,System.String]");
内容的提问来源于stack exchange,提问作者Ricky Ho
相关产品推荐
相关产品推荐

