在 C# 中,为什么 String 是一种行为类似于值类型的引用类型? [英] In C#, why is String a reference type that behaves like a value type?

查看:30
本文介绍了在 C# 中,为什么 String 是一种行为类似于值类型的引用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String 是一种引用类型,尽管它具有值类型的大部分特征,例如不可变和 == 重载以比较文本而不是确保它们引用相同的对象.

那为什么字符串不只是一种值类型?

解决方案

字符串不是值类型,因为它们可能很大,并且需要存储在堆中.值类型(在迄今为止的所有 CLR 实现中)存储在堆栈中.堆栈分配字符串会破坏各种事情:堆栈只有 1MB 用于 32 位和 4MB 用于 64 位,您必须将每个字符串装箱,导致复制损失,您不能实习字符串和内存使用会气球等...

(添加了关于值类型存储是一个实现细节的说明,这导致我们有一个值语义不是从 System.ValueType 继承的类型.谢谢 Ben.)>

A String is a reference type even though it has most of the characteristics of a value type such as being immutable and having == overloaded to compare the text rather than making sure they reference the same object.

Why isn't string just a value type then?

解决方案

Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...

(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)

这篇关于在 C# 中,为什么 String 是一种行为类似于值类型的引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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