How to clone an inherited object?

后端 未结 3 1941
深忆病人
深忆病人 2021-01-22 08:24

I\'ve got a Tile class with this method:

    public object Clone()
    {
        return MemberwiseClone();
    }

And another class

3条回答
  •  死守一世寂寞
    2021-01-22 08:39

    As I see it, there are four main classes of object, with respect to cloning:

    1. Those which cannot be cloned without breaking something
    2. Those which make no public promise of cloneability, but can be nicely cloned using MemberwiseClone
    3. Those which make no public promise of cloneability, but can be cloned via some means other than MemberwiseClone
    4. Those which publicly advertise cloneability on behalf of themselves and derived classes.
    Unfortunately, there's generally no nice way to distinguish #1 and #2 unless a type obscures the MemberwiseClone method. I like to refer to type #3 as semi-cloneable.

    A semi-cloneable object should support a protected virtual method called something like CloneBase which will return either Object or the base class type (it won't matter much in practice); the lowest-level CloneBase method should call MemberwiseClone and do whatever is necessary to fix up the cloned object. Any derived class which supports cloning should have a public Clone method which simply calls CloneBase and typecasts the result. Any derived-class logic necessary to fix up and object after base-class-level cloning should go in an override of CloneBase.

    If there may be any need for a derived class which does not support cloning, then make public a semi-cloneable class and inherit from that class a CloneableWhatever which does nothing except add the public Clone method. In that way, non-cloneable classes can derive from the semi-cloneable class, and cloneable ones can derive from CloneableWhatever.

提交回复
热议问题