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

2019-04-01 10:53发布

问题:

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.