Clone derived class from base class method

后端 未结 7 2228
萌比男神i
萌比男神i 2021-02-08 17:09

I have an abstract base class Base which has some common properties, and many derived ones which implement different logic but rarely have additional fields.

<
7条回答
  •  醉酒成梦
    2021-02-08 18:07

    Just override the Clone and have another method to CreateInstance then do your stuff.

    This way you could have only Base class avoiding generics.

    public Base
    {
        protected int field1;
        protected int field2;
        ....
    
        protected Base() { ... }
    
        public virtual Base Clone() 
        { 
            var bc = CreateInstanceForClone();
            bc.field1 = 1;
            bc.field2 = 2;
            return bc;
        }
    
        protected virtual Base CreateInstanceForClone()
        {
            return new Base(); 
        }
    }
    
    
    public A : Base 
    {     
        protected int fieldInA;
        public override Base Clone() 
        { 
            var a = (A)base.Clone();
            a.fieldInA =5;
            return a;
        }
    
        protected override Base CreateInstanceForClone()
        {
            return new A(); 
        }
    }
    

提交回复
热议问题