When (deep) Cloning, use String.Copy or str1 = str2?

折月煮酒 提交于 2019-12-05 02:36:44

问题


When (deep) Cloning a custom object, should I use clone.str1 = String.Copy(obj.str1) or clone.str1 = obj.str1?

I'd prefer the latter - shorter and quicker, but is it "safe"?

I'd point to this thread, but, however, not sure what to use.


回答1:


Yes - the latter choice (simple assignment) is safe for strings (in managed code), as this code illustrates:

    string s1 = "Initial Value";
    string s2 = s1;

    Console.WriteLine("String1: " + s1);
    Console.WriteLine("String2: " + s2);

    s1 = "New Value";

    Console.WriteLine("String1 - after change: " + s1);
    Console.WriteLine("String2 - after change: " + s2);

Output:

String1: Initial Value
String2: Initial Value
String1 - after change: New Value
String2 - after change: Initial Value

Strings are immutable - so when you change s1, you are really creating a new string and assigning it. The reference of s2 remains pointing to the old instance.




回答2:


Calling String.Copy will create a separate copy of the string.
Since strings are immutable, there's no need to do that.




回答3:


When deep cloning, why not just use a BinaryFormatter instead?

See this link.

Here's the code I wrote at that link:

public Automobile Clone()
{
    Automobile result = null;
    using (MemoryStream ms = new MemoryStream())
    {
         BinaryFormatter bf = new BinaryFormatter();
         bf.Serialize(ms, this);
         ms.Position = 0;
         result = (Automobile)bf.Deserialize(ms);
     }
     return result;
}



回答4:


when deep cloning, you need to clone every mutable value. String is mutable on .NET, so yes, you should clone it.

edit: whoops ... seems they are immutable, so no, you don't need to.



来源:https://stackoverflow.com/questions/2334527/when-deep-cloning-use-string-copy-or-str1-str2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!