如何正确继承克隆方法?

时间:2018-08-08 00:17:48

标签: c# inheritance override clone cloning

我有一个基类(A)和一个交付班(B)。他们继承了我制作的ICloneable<>通用接口:

interface ICloneable<T>
{
    T Clone();
}

我想覆盖A.Clone()中的B方法,但是,B.Clone()返回类型为B而不是A的对象,但是,覆盖不允许这样做。

我有某种解决方法,但是我发现它真的很丑:

class A : ICloneable<A>
{
    virtual A Clone() => /*magic*/;
}
class B : A, ICloneable<B>
{
    B CloneAsB() => /*other kind of magic*/;
    override A Clone() => CloneAsB();
}

(我还添加了非泛型ICloneable的显式实现,但在示例中未显示。)

是否有更好的方法来实现这一目标,而不必使用 false 克隆方法?

1 个答案:

答案 0 :(得分:0)

我发现了一个更好的解决方法:使用非泛型ICloneable<A>.Clone()将泛型ICloneable.Clone()方法的调用向下传递到继承层次结构中可能会很有用,如下所示:

class A : ICloneable<A>, ICloneable
{
    A Clone() => (A) ((ICloneable) this).Clone(); //This will call ICloneable.Clone in class B if the type of the object is B!

    //If object is of type B, not this but the derived method is called:
    object ICloneable.Clone() => /*Cloning, if object is an instance of A*/;
}
class B : A, ICloneable<B>
{
    new B Clone() => (B) ((ICloneable) this).Clone(); //This will call ICloneable.Clone in a derived type if object is of more derived type!

    //If object is of even more derived type, not this but the method of the derived class is called:
    object ICloneable.Clone() => /*Cloning, if object is an instance of B*/;
}
//Same implementation for class C...

其优点是,所有方法都不必显式检查对象的类型(即,在类A中,Clone()不必检查对象的类型是否为{{ 1}})。