When (deep) Cloning, use String.Copy or str1 = str2?
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 th开发者_如何学Cis thread, but, however, not sure what to use.
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.
Calling String.Copy
will create a separate copy of the string.
Since strings are immutable, there's no need to do that.
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;
}
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.
精彩评论