关于C#字符串的问题:不可抗力和克隆

Jie*_*eng 2 c#

我正在阅读Accelerated C#2010.并且有一些问题

问题1

String的实例是不可变的,因为一旦你创建它们,你就无法改变它们

怎么回事呢.我有一段时间没有使用过C#,而且我刚刚开始,所以即使在语法中我也许错了.

string str1 = "this is a string"; // i hope my syntax is right 
str1 = "this is a NEW string"; // i think i can do this right? 
Run Code Online (Sandbox Code Playgroud)

问题2

如果在字符串上调用ICloneable.Clone方法,则会得到一个指向与源相同的字符串数据的实例.事实上,ICloneable.Clone只是返回对此的引用

如果这是真的,那就意味着

string str1 = "string 1";
// i hope my syntax is right too. i am really not sure about this
string str2 = str1.Clone(); 
str2 = "modified string"; // will str1 be modified too? 
Run Code Online (Sandbox Code Playgroud)

Hei*_*nzi 13

string str1 = "this is a string"; // i hope my syntax is right 
str1 = "this is a NEW string"; // i think i can do this right? 
Run Code Online (Sandbox Code Playgroud)

当然!string是一个引用类型(一个指针,如果你想这样看,就这样看),所以在第2行,你将变量str1指向内存中的另一个(常量)字符串.原始字符串不会更改,它不再被引用.

string str1 = "string 1";
string str2 = str1.Clone(); // i hope my syntax is right too. i am really not sure about this
str2 = "modified string"; // will str1 be modified too? 
Run Code Online (Sandbox Code Playgroud)

不,因为你没有修改"string 1".在第2行之后,它看起来像这样:

memory            "string 1"
                    ^    ^ 
                    |    |
stack             str1  str2
Run Code Online (Sandbox Code Playgroud)

在第3行之后,它看起来像这样:

memory            "string 1"     "modified string"
                      ^              ^
                      |              |
stack                str1           str2
Run Code Online (Sandbox Code Playgroud)

  • 重要的是要注意,在调用Clone()方法之后引用看起来像图的原因是因为字符串的Clone()方法被实现为返回'this'.通常,人们会期望Clone()返回一个具有相同内容的新实例(但这对于不可变类型几乎没有实现,因此String的优化是合理的). (3认同)