How to deep copy a class without marking it as Serializable

前端 未结 7 491
自闭症患者
自闭症患者 2021-01-04 00:09

Given the following class:

class A
{
    public List ListB;

    // etc...
}

where B is another class that may inheri

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 00:41

    I stopped using serialization for deep copying anyway, because there is not enough control (not every class needs to be copied the same way). Then I started to implement my own deep copy interfaces and copy every property in the way it should be copied.

    Typical ways to copy a referenced type:

    • use copy constructor
    • use factory method (eg. immutable types)
    • use your own "Clone"
    • copy only reference (eg. other Root-Type)
    • create new instance and copy properties (eg. types not written by yourself lacking a copy constructor)

    Example:

    class A
    {
      // copy constructor
      public A(A copy) {}
    }
    
    // a referenced class implementing 
    class B : IDeepCopy
    {
      object Copy() { return new B(); }
    }
    
    class C : IDeepCopy
    {
      A A;
      B B;
      object Copy()
      {
        C copy = new C();
    
        // copy property by property in a appropriate way
        copy.A = new A(this.A);
        copy.B = this.B.Copy();
      }
    }
    

    You may think that this a huge amount of work. But at the end, it is easy and straight forward, can be tuned where needed and does exactly what you need.

提交回复
热议问题