string.Clone()有什么用?

Ars*_*eny 28 .net c# string .net-2.0

有2个代码示例:#1

 string str1 = "hello";
 string str2 = str1; //reference to the same string
 str1 = "bye"; //new string created
Run Code Online (Sandbox Code Playgroud)

和#2

string str3 = "hello";
string str4 = (string)str3.Clone();//reference to the same string
str3 = "bye";//new string created
Run Code Online (Sandbox Code Playgroud)

看起来他们是相同的不是吗?那么使用Clone()有什么好处?当我不能使用代码#1但代码#2时,你能给我一个例子吗?

Eli*_*sha 25

这很有用,因为string实现了ICloneable,因此您可以为ICloneable项的集合创建克隆的副本.当集合只是字符串时,这很无聊,但是当集合包含多个实现ICloneable的类型时,它很有用.

至于复制单个字符串它没有用,因为它通过设计返回对它自己的引用.


Jon*_*han 21

不是直接回答你的问题,但是如果你想要实际克隆一个字符串,你可以使用静态string.Copy()方法.