是字符串值类型或引用类型? [英] Is string a value type or a reference type?

查看:199
本文介绍了是字符串值类型或引用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是一个字符串值类型或引用类型?

我无法找到一个好的解释,这...

解决方案

  Console.WriteLine(typeof运算(字符串).IsClass); // 真正
 

这是一个引用类型。

这不可能是一个值类型,值类型需要堆栈等作为参考型已知大小,在引用的大小是事先知道,即使如果字符串的大小不是

它的表现得的像你期望的行为值类型,因为它是不可变的;即一旦创建它不换水。但也有很多其他的不可变的引用类型。委托情况下,例如

* =里的StringBuilder 除,但你永远也看不到它,而它是这样做的......

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's a reference type.

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.

*=except for inside StringBuilder, but you never see it while it is doing this...

这篇关于是字符串值类型或引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆