gpt4 book ai didi

c# - String 泛型参数被视为值类型还是引用类型?

转载 作者:行者123 更新时间:2023-11-30 13:30:26 25 4
gpt4 key购买 nike

来自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.

我由此推断是否正确,虽然 string 数据类型在 C# 和 CLR 中都具有值类型语义,但是用 string 实例化的泛型类型> 类型参数将使用与其他引用类型相同的专用泛型类型,而不是像其他值类型那样拥有自己的类型?自 V2 引入泛型以来,无论哪种方式,这种行为都一样吗?

最佳答案

string 在各个方面都是引用类型。它有 "value-type semantics"在维基百科意义上,但这并没有使它成为 MSDN 中使用的术语中的值类型。在常见的CLR和C#术语中,将所有非指针类型分为“引用类型”或“值类型”,字符串绝对是引用类型。请注意,您也可以轻松地构建自己的具有值语义的引用类型 - 但它在规范关心的各个方面仍然是一个引用类型。

关于c# - String 泛型参数被视为值类型还是引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35294236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com