在C#中,为什么是String,它就像一个值类型引用类型? [英] In C#, why is String a reference type that behaves like a value type?

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

问题描述

一个字符串是即使它有最值类型的特性,例如是不可改变的,有==超载文本比较,而不是确保他们引用同一个对象的引用类型。

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?

推荐答案

字符串是不是值类型,因为它们可以是巨大的,并且需要储存在堆上。值类型是(作为尚未CLR的全部实现)存储在堆栈上。堆栈分配的字符串将打破各种各样的东西:堆栈只​​有1MB,你不得不盒每个字符串,招致副本点球,你不能实习生字符串和内存使用情况将气球等...

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, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...

(编辑:。增加了澄清值类型存储是一个实现细节,才导致这种情况下,我们有值语义学不是从System.ValueType由于本继承类型)

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

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