string.Clone()有什么用?

有两个代码示例:#1

string str1 = "hello"; string str2 = str1; //reference to the same string str1 = "bye"; //new string created 

和#2

 string str3 = "hello"; string str4 = (string)str3.Clone();//reference to the same string str3 = "bye";//new string created 

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

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

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

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

上面代码中的.Clone()与简单赋值相同。 此外,字符串是不可变的,因此它将在写入时复制两种情况。

.Clone()在使用不同类型的情况下会更有用,它们实现相同的接口(在本例中为IClonable),因为您无法使用简单的赋值,但仍然可以转换返回的对象通过Clone()到ICloneable并分配该引用。 例如,使用ICloneable元素迭代通用集合。