有什么用string.Clone的()?什么用、string、Clone

2023-09-02 10:32:31 作者:正在努力加载

也有code两个例子:  #1

there are 2 examples of code: # 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?

looks like they are identical aren't they? so what is the benefit to use Clone()? can you give me an example when I cannot use code#1 but code#2 ?

推荐答案

这是因为字符串实现了有用的 ICloneable 的,所以你可以对 ICloneable 项目。这是无聊的时候收集是一个字符串而已,但是当集合包含实现多种类型的 ICloneable 的它是有用的。

This is useful since string implements ICloneable, so you can create a copy of clones for a collection of ICloneable items. This is boring when the collection is of strings only, but it's useful when the collection contains multiple types that implement ICloneable.

至于复制它没有采用单一字符串,因为它返回由设计到自身的引用。

As for copying a single string it has no use, since it returns by design a reference to itself.