作者:sx-March23 | 来源:互联网 | 2023-09-15 11:20
从MSDN Generics in the Run Time文件我注意到:
When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate locations in the MSIL. Specialized generic types are created one time for each unique value type that is used as a parameter.
和
Generics work somewhat differently for reference types. The first time a generic type is constructed with any reference type, the runtime creates a specialized generic type with object references substituted for the parameters in the MSIL. Then, every time that a constructed type is instantiated with a reference type as its parameter, regardless of what type it is, the runtime reuses the previously created specialized version of the generic type. This is possible because all references are the same size.
我是否正确地推断,尽管字符串数据类型在C#和CLR中都具有值类型语义,但使用字符串类型参数实例化的泛型类型将使用与其他引用类型相同的专用泛型类型,而不是比拥有自己的其他价值类型呢?无论哪种方式,这种行为都是相同的,因为V2引入了泛型?
解决方法:
string是各种方式的引用类型.它在维基百科意义上有“value-type semantics”,但这并不是MSDN中使用的术语中的值类型.在将所有非指针类型划分为“引用类型”或“值类型”的公共CLR和C#术语中,字符串绝对是引用类型.请注意,您也可以使用值语义轻松构建自己的引用类型 – 但它仍然是规范所关注的每种方式的引用类型.