【发布时间】:2010-12-01 17:10:24
【问题描述】:
为什么它不显示真实类型(例如:List
这个奇怪的(对我来说)符号从何而来?
【问题讨论】:
标签: .net generics reflection types
为什么它不显示真实类型(例如:List
这个奇怪的(对我来说)符号从何而来?
【问题讨论】:
标签: .net generics reflection types
具有一个类型参数的泛型 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 并不要求泛型类型以这样的方式命名。这只是编译器能够选择正确类型的约定。
【讨论】:
List<T> 变为 List`1。它是“开放的泛型类型定义”。 List<string> 的封闭定义将变为 List`1[System.String]。
它不显示List<string>,因为这是依赖于 C# 的语法。 .Net 源代码中的列表可以声明为 List<string>、List(Of String) 或其他 60 种左右可以编译为 MSIL 的语言/语法中的任何一种。
所以您看到的是更通用的 MSIL 语法。
`1 表示它是一个具有一个泛型参数的 List。
【讨论】:
`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]
【讨论】:
Dictionary<string, int> 是 Dictionary`2[System.String,System.Int32],而不是 Dictionary`1,因为它有 两个类型参数。