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

后端 未结 3 858
情话喂你
情话喂你 2020-12-01 20:28

there are 2 examples of code: # 1

 string str1 = \"hello\";
 string str2 = str1; //reference to the same string
 str1 = \"bye\"; //new string created


        
相关标签:
3条回答
  • 2020-12-01 21:20

    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.

    0 讨论(0)
  • 2020-12-01 21:30

    .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.

    0 讨论(0)
  • 2020-12-01 21:33

    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.

    0 讨论(0)
提交回复
热议问题