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

前端 未结 8 1536
隐瞒了意图╮
隐瞒了意图╮ 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:39
    1. You could use reflection to loop all variables and copy them.(Slow) if its to slow for you software you could use DynamicMethod and generate il.
    2. serialize the object and deserialize it again.
    0 讨论(0)
  • 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};
      }
    }
    
    0 讨论(0)
提交回复
热议问题