Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

c# - what's the use of string.Clone()?

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...