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

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

    The best way is by serializing your object, then returning the deserialized copy. It will pick up everything about your object, except those marked as non-serializable, and makes inheriting serialization easy.

    [Serializable]
    public class ParentObj: ICloneable
    {
        private int myA;
        [NonSerialized]
        private object somethingInternal;
    
        public virtual object Clone()
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, this);
            object clone = formatter.Deserialize(ms);
            return clone;
        }
    }
    
    [Serializable]
    public class ChildObj: ParentObj
    {
        private int myB;
    
        // No need to override clone, as it will still serialize the current object, including the new myB field
    }
    

    It is not the most performant thing, but neither is the alternative: relection. The benefit of this option is that it seamlessly inherits.

提交回复
热议问题