首页 > 解决方案 > 执行时返回 null Type.GetType("System.Collections.Generic.SortedDictionary`2[System.String,System.String]");

问题描述

我正在尝试获取 SortedDictionary 的字符串化对象类型的类型,但它始终返回空值。但是,它适用于字典。

有用: Type.GetType("System.Collections.Generic.Dictionary`2[System.String,System.String]");

不起作用并且总是返回一个空值: Type.GetType("System.Collections.Generic.SortedDictionary`2[System.String,System.String]");

为什么以及如何解决这个问题?谢谢。

标签: c#typesgettype

解决方案


Type.GetType(string)当此类型位于当前正在执行的程序集中或位于mscorlib.dll. 对于其他类型,需要assembly qualified name指定。

Dictionary<TKey, TValue>位于mscorlib.dll(for .NET Framework) 因此

Type.GetType("System.Collections.Generic.Dictionary`2[System.String,System.String]");

能够返回其类型。

SortedDictionary<TKey, TValue>位于System.dll因此

Type.GetType("System.Collections.Generic.SortedDictionary`2[System.String,System.String]");

返回null

要获取类型,SortedDictionary<TKey, TValue>我们需要指定其assembly qualified name

Type.GetType(
    "System.Collections.Generic.SortedDictionary`2[" +
    "[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
    "[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]" +
    ", System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

这是演示它的演示。


推荐阅读