【问题标题】:Why does the runtime shows the generic types as "GenericType`n"?为什么运行时将泛型类型显示为“GenericType`n”?
【发布时间】:2010-12-01 17:10:24
【问题描述】:

为什么它不显示真实类型(例如:List 而不是 List`1)?
这个奇怪的(对我来说)符号从何而来?

【问题讨论】:

    标签: .net generics reflection types


    【解决方案1】:

    具有一个类型参数的泛型 List<T> 的 CLR 名称是

    System.Collections.Generic.List`1
    

    List<T> 是命名该类型的 C# 风格。

    符号是一种约定,使您能够通过参数计数重载泛型类型。如果您使用两个类型参数(例如 List<T,U>)声明一个名为 List 的类,编译器将能够选择正确的一个。它将被命名为:

    System.Collections.Generic.List`2
    

    一个非泛型的List 类将被命名:

    System.Collections.Generic.List
    

    请注意,CLR 并不要求泛型类型以这样的方式命名。这只是编译器能够选择正确类型的约定。

    【讨论】:

    • 我认为 CLI 没有删除泛型类型?如果不是,当“List”变成List`1时,“String”在哪里?
    • List<T> 变为 List`1。它是“开放的泛型类型定义”。 List<string> 的封闭定义将变为 List`1[System.String]。
    【解决方案2】:

    它不显示List<string>,因为这是依赖于 C# 的语法。 .Net 源代码中的列表可以声明为 List<string>List(Of String) 或其他 60 种左右可以编译为 MSIL 的语言/语法中的任何一种。

    所以您看到的是更通用的 MSIL 语法。

    `1 表示它是一个具有一个泛型参数的 List。

    【讨论】:

      【解决方案3】:

      `1 是泛型类型的 MSIL 语法 - List<T> 是特定于 C# 的。更多 MSIL 示例:

      List<T> == System.Collections.Generic.List`1
      
      List<string> == System.Collections.Generic.List`1[System.String]
      
      Dictionary<string, int> == 
         System.Collections.Generic.Dictionary`2[System.String, System.Int32]
      

      【讨论】:

      • 我认为你没有抓住重点。 `1 没有为 CLR 定义泛型类。在 IL 级别,可以任意命名一个泛型类。这是一种解决高级语言重载泛型类型之间歧义的方法。它声明类型的类型参数的数量,以便您可以通过泛型参数的数量重载类型。你的例子是错误的。 Dictionary&lt;string, int&gt; 是 Dictionary`2[System.String,System.Int32],而不是 Dictionary`1,因为它有 两个类型参数。
      猜你喜欢
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      相关资源
      最近更新 更多