开发者

C# Need to deep copy an object [duplicate]

This question already has answers here: Create a Deep Copy in C# (9 answer开发者_JAVA技巧s) Closed 8 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜