有2个代码示例: # 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() 有什么好处呢?当我不能使用 code#1 而只能使用 code#2 时,你能举个例子吗?
最佳答案
这很有用,因为字符串实现了 ICloneable,因此您可以为 ICloneable 项的集合创建克隆副本。当集合仅包含字符串时,这很无聊,但当集合包含多个实现 ICloneable 的类型时,这很有用。
至于复制单个字符串,它没有用,因为它按设计返回对自身的引用。
关于c# - string.Clone() 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3465377/