C# Need to deep copy an object [duplicate]
I need to deep copy an object from a class that I made to another object from the same class, I dont want to shallow copy and I dont want to use the serialization method is there any other easy methods to use??
One cheap way is to serialize it then deserialize it straight back using binary serialization.
MyObject myobj = new MyObject();
// ...
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, myObj);
MemoryStream ms2 = new MemoryStream(ms.ToArray());
var myobj2 = (MyObject)formatter.Deserialize(ms2);
Implement IClonable and provide the cloning yourself in the Clone
method.
精彩评论