理解c#中字符串不变性的示例

时间:2014-09-15 17:01:00

标签: c#

“字符串在c#中是不可变的”是什么意思。我需要一些例子来理解这一点。我找不到一些适当的例子来理解这个

2 个答案:

答案 0 :(得分:1)

这意味着如果您指定

string s = "Hello";

你无法修改字符串s。因此,如果你这样做

s = "Goodbye";

字面意思"你好"没有被修改,而是一个新的文字" Goodbye"被分配给s。

答案 1 :(得分:-2)

搜索文本“字符串在c#中是不可变的”我找到:http://msdn.microsoft.com/en-us/library/362314fe.aspx

这似乎是说字符串永远不会更改对象,它们总是被销毁并重新创建。

Per Microsoft:

Strings are immutable--the contents of a string object cannot be changed after the 
object is created, although the syntax makes it appear as if you can do this. 
For example, when you write this code, the compiler actually creates a new string object 
to hold the new sequence of characters, and that new object is assigned to b. The string "h" 
is then eligible for garbage collection.

string b = "h";
b += "ello";