How to deep copy a class without marking it as Ser

2020-03-01 04:57发布

Given the following class:

class A
{
    public List<B> ListB;

    // etc...
}

where B is another class that may inherit/contain some other classes.


Given this scenario:

  1. A is a large class and contains many reference types
  2. I cannot mark B as [Serializable] as I don't have access to source code of B

The following methods to perform deep copying do not work:

  1. I cannot use ICloneable or MemberwiseClone as class A contains many reference types
  2. I cannot write a copy constructor for A, as the class is large and continuously being added to, and contains classes (like B) that cannot be deep copied
  3. I cannot use serialization as I cannot mark a contained class (like B, where no source code available) as [Serializable]

How can I deep copy class A?

7条回答
看我几分像从前
2楼-- · 2020-03-01 05:48

your interface IDeepCopy is exactly what ICloneable specifies.

class B : ICloneable
{
     public object Clone() { return new B(); }
}

and with more friendly implementation :

class B : ICloneable
{
     public B Clone() { return new B(); }
     // explicit implementation of ICloneable
     object ICloneable.Clone() { return this.Clone(); }
}
查看更多
登录 后发表回答