字符串是值类型还是引用类型.. [英] Is string a value type or Reference type..
本文介绍了字符串是值类型还是引用类型..的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我是C#的新手。任何人都可以告诉我C#.net中的字符串是值类型还是引用类型。有些人说..it是一个值类型,有人说它是Refernce类型,有人说它是一个引用类型但是就像一个值类型......所以很困惑.Kinldy帮我解决了String在C#中的表现如何?
问候
Chaithanya M
Hi Everyone,
I am a newbie to C#.Can anyone tell me whether string is a value type or reference type in C#.net.Some sources say ..it is a value type, some say it is Refernce type and some say it is a reference type but acts like a value type..so confused..Kinldy help me how "String" behaves in C#?
regards
Chaithanya M
推荐答案
这是一个引用类型,但在所有方面模拟值语义
。例如,当您比较两个引用不同的字符串时,比较(==
)可以为真 - 它们将按内容进行比较。但是,这很容易:您可以实现自己的身份规则,覆盖System.Object.Equals,System.Object.GetHashCode(必需),并可选择定义自定义运算符==
和!=
。
如果查看属性system.String.Intern
,您可以理解使用字符串引用的本质和system.String.IsInterned
:
http://msdn.microsoft.com/en-us/library/system.string.intern.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system.string.isinterned.aspx [ ^ ]。
字符串的一个重要实际问题:它们是不可变的(与可变数组相反)。因此,出于性能原因,不应在循环中使用+。对于此(以及许多其他)目的,请使用System.Text.StringBuilder
。
-SA
This is a reference type but simulatingvalue semantic
in all aspects. For example, when you compare two referentially different strings, comparison (==
) can be true — they are compared by the content. However, this is easy part: you can implement your own identity rules overriding System.Object.Equals, System.Object.GetHashCode (required) and optionally define custom operators "==
" and "!=
".
You can understand the essence of working with string references if you look at the propertiessystem.String.Intern
andsystem.String.IsInterned
:
http://msdn.microsoft.com/en-us/library/system.string.intern.aspx[^],
http://msdn.microsoft.com/en-us/library/system.string.isinterned.aspx[^].
One important practical issue with the strings: they are immutable (in contrast to mutable arrays). Therefore, for performance reasons one should never use "+" in cycles. For this (and many other) purposes, useSystem.Text.StringBuilder
.
—SA
检查MSDN: string(C#reference) [ ^ ]
第二行声明:
尽管string是引用类型,但是相等运算符(==和!=)被定义为比较字符串对象的值,而不是引用。这使得对字符串相等性的测试更加直观。
因此它是一种引用类型,但具有一些值类型行为;)
Check MSDN: string (C# reference)[^]
The second line states:
Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive.
So it is a reference type but with some value-type behaviour ;)
在这里查看字符串 [ ^ ]
这篇关于字符串是值类型还是引用类型..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文