【问题标题】:Can not get Type of LinkedList`T with Type.GetType(string)无法使用 Type.GetType(string) 获取 LinkedList`T 的类型
【发布时间】:2020-02-23 09:40:17
【问题描述】:

我可以通过以下方式获取List<T>Dictinary<TK, TVal>等的类型信息:

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

但是无法获取LinkedList<T>的类型信息:

Type.GetType("System.Collections.Generic.LinkedList`1[System.String]") // Returns NULL
Type.GetType("System.Collections.Generic.LinkedList`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") // Also returns NULL

检查LinkedList<string>的组装

typeof(LinkedList<decimal>).Assembly

给予:

System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

使用 .NET 标准 2.0.3。

【问题讨论】:

    标签: c# .net reflection


    【解决方案1】:

    尝试为System.Collections.Generic.LinkedList1`类型指定完全限定的程序集名称

    var type = Type.GetType("System.Collections.Generic.LinkedList`1[System.String], System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
    

    或者只使用程序集名称

    type = Type.GetType("System.Collections.Generic.LinkedList`1[System.String], System");
    

    List&lt;T&gt;mscorlib.dll 的一部分,LinkedList&lt;T&gt; 是否是 System.dll 的一部分

    你几乎就在这里

    Type.GetType("System.Collections.Generic.LinkedList`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]") // Also returns NULL
    

    但是您已经为泛型类型参数指定了完全限定名称,即System.String 类型,而不是LinkedList

    【讨论】:

    • OP:请注意,LinkedList&lt;T&gt; 位于 .NET Framework 的 System 程序集中,但它位于 .NET Core 的 System.Collections 程序集中.见this。如果您对程序集名称进行硬编码,您将被绑定到特定的实现。如果你可以改用typeof(LinkedList&lt;string&gt;),你应该这样做。
    • 你绝对是对的@madreflection。在编译时获取类型信息很简单,但我的挑战是在运行时从用户定义的字符串中获取类型信息。 PS:我尝试安装System.Collections 包,但在您发表评论之前失败了。谢谢你,你的评论对我也有帮助。
    【解决方案2】:

    显然,这是因为List&lt;&gt; 是在mscorlib.dll 中定义的,而LinkedList&lt;&gt; 是在System.dll 中定义的(来自GAC)。

    因此,您必须在动态加载程序集时明确表示程序集名称:

    Type.GetType("System.Collections.Generic.LinkedList`1, System")
    

    来自Documentation

    如果类型在当前执行的程序集中或在 Mscorlib.dll 中, 提供由其命名空间限定的类型名称就足够了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 2011-04-16
      • 2022-01-19
      相关资源
      最近更新 更多