I need to implement C# deep copy constructors with inheritance. What patterns are there to choose from?

前端 未结 8 1601
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 08:47

I wish to implement a deepcopy of my classes hierarchy in C#

public Class ParentObj : ICloneable
{
    protected int   myA;
    public virtual Object Clone          


        
8条回答
  •  梦谈多话
    2020-12-29 09:35

    try the serialization trick:

    public object Clone(object toClone)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms= new MemoryStream();
        bf.Serialize(ms, toClone);
        ms.Flush();
        ms.Position = 0;
        return bf.Deserialize(ms);
    }
    

提交回复
热议问题