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

前端 未结 8 1600
隐瞒了意图╮
隐瞒了意图╮ 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:31

    You should use the MemberwiseClone method instead:

    public class ParentObj : ICloneable
    {
        protected int myA;
        public virtual Object Clone()
        {
            ParentObj newObj = this.MemberwiseClone() as ParentObj;
            newObj.myA = this.MyA; // not required, as value type (int) is automatically already duplicated.
            return newObj;
        }
    }
    
    public class ChildObj : ParentObj
    {
        protected int myB;
        public override Object Clone()
            {
                 ChildObj newObj = base.Clone() as ChildObj;
                 newObj.myB = this.MyB; // not required, as value type (int) is automatically already duplicated
    
                 return newObj;
            }
    }
    

提交回复
热议问题