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

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

    Try to use the following [use the keyword "new"]

    public class Parent
    {
      private int _X;
      public int X{ set{_X=value;} get{return _X;}}
      public Parent copy()
      {
         return new Parent{X=this.X};
      }
    }
    public class Child:Parent
    {
      private int _Y;
      public int Y{ set{_Y=value;} get{return _Y;}}
      public new Child copy()
      {
         return new Child{X=this.X,Y=this.Y};
      }
    }
    

提交回复
热议问题