【问题标题】:Returns null when executing Type.GetType("System.Collections.Generic.SortedDictionary`2[System.String,System.String]");执行时返回 null Type.GetType("System.Collections.Generic.SortedDictionary`2[System.String,System.String]");
【发布时间】:2020-08-25 03:40:04
【问题描述】:

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

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

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

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

【问题讨论】:

标签: c# types gettype


【解决方案1】:

方法 Type.GetType(string) 仅当该类型位于当前正在执行的程序集中或位于 mscorlib.dll 中时,才能按其名称返回类型。对于其他类型,它需要指定 assembly qualified name

Dictionary<TKey, TValue> 位于mscorlib.dll(对于.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");

这里是demo 显示它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2012-02-01
    • 2011-11-18
    相关资源
    最近更新 更多