The easiest way to deep copy an object is to serialize and deserialize it. Here’s an example from a project I’m working on:
[Serializable()]
public class Board :ICloneable, ISerializable {
// ...
object ICloneable.Clone()
{
return this.Clone();
}
public Board Clone()
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
return (Board)bf.Deserialize(ms);
}
}
public class Board :ICloneable, ISerializable {
// ...
object ICloneable.Clone()
{
return this.Clone();
}
public Board Clone()
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
return (Board)bf.Deserialize(ms);
}
}
You might need to implement the serialization functions too for this to work, however.
Leave a comment