字符串是值类型还是引用类型? [英] Is string a value type or a reference type?
问题描述
字符串是值类型还是引用类型?
Is string a value type or a reference type?
我只是找不到对此的好的"解释...
I just can't find a "good" explanation for this...
推荐答案
Console.WriteLine(typeof(string).IsClass); // true
这是一个引用类型.
它不能是值类型,因为值类型需要已知堆栈大小等.作为引用类型,引用的大小是预先知道的,即使如果字符串的大小不是.
It can't be a value-type, as value-types need a known size for the stack etc. As a reference-type, the size of the reference is known in advance, even if the size of the string isn't.
它行为就像您期望值类型的行为一样,因为它是不可变的;即它一旦创建就不会*改变.但是还有很多其他不可变的引用类型.例如,委托实例.
It behaves like you expect a value-type to behave because it is immutable; i.e. it doesn't* change once created. But there are lots of other immutable reference-types. Delegate instances, for example.
*=除了在 StringBuilder
内部,但在执行此操作时您永远不会看到它...
*=except for inside StringBuilder
, but you never see it while it is doing this...
这篇关于字符串是值类型还是引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!