c# - string.Clone() 有什么用?

标签 c# .net string .net-2.0

有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/

相关文章:

c# - 将 double 转换为字符串

c# - 如何从进程内存中删除字符串?

string - 如何以特定编号访问字符串中的char?

c# - 如何在没有用户提示的情况下添加到日历 UWP C#

c# - 我在 Azure Function Monitor 日志屏幕中看到条目。如何在 Application Insights 中找到它们?

c# - 配置 filesystemwatcher 使其仅在文件被完全复制时引发创建的事件

.net - 整个应用程序 VB .Net 的 Keydown 事件

c# - 如何保护我的 .net winforms 程序集不受客户客户的影响

android - 在不使用 nameValuePairs 的情况下使用 HttpPost 在 Android 上发送字符串

string - 如何使用字符串为 jQueryUI Datepicker 设置 minDate/maxDate?