string.Clone() 有什么用?
有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 时,你能给我一个例子吗?
there are 2 examples of code:
# 1
string str1 = "hello";
string str2 = str1; //reference to the same string
str1 = "bye"; //new string created
and # 2
string str3 = "hello";
string str4 = (string)str3.Clone();//reference to the same string
str3 = "bye";//new string created
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这很有用,因为字符串实现了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.
不是直接回答您的问题,但如果您希望实际克隆字符串,则可以使用静态
string.Copy()
方法。Not directly in answer to your question, but in case you are looking to actually clone a string, you can use the static
string.Copy()
method.上面代码中的.Clone()与简单赋值相同。此外,字符串是不可变的,因此在这两种情况下它都会在写入时复制。
.Clone() 在您使用不同类型、实现相同接口(在本例中为 IClonable)的情况下会更有用,因为您无法使用简单的赋值,但仍然可以转换返回的对象通过 Clone() 到 ICloneable 并分配该引用。例如,使用 ICloneable 元素迭代通用集合。
.Clone() in the above code is the same as the simple assignment. Also, string is immutable, so it will copy on write in both cases.
.Clone() would be a lot more useful in cases, where you are using different types, that implement the same interface (in this case IClonable) as you would not be able to use a simple assignment, but could still cast the object returned by Clone() to ICloneable and assign that reference. For instance iterating through a generic collection with ICloneable elements.