【问题标题】:How to inherit cloning methods properly?如何正确继承克隆方法?
【发布时间】:2019-01-15 03:34:06
【问题描述】:

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

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

我想覆盖B 中的A.Clone() 方法,但是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 克隆方法?

【问题讨论】:

  • c# 还不支持。您的解决方法很丑陋,因为您仍在强迫自己这样做。实现这一点的更好方法是不使用 ICloneable 接口,让每个类都有自己的克隆方法,而无需虚拟/覆盖。

标签: c# inheritance overriding clone cloning


【解决方案1】:

我找到了一个更好的解决方法:使用非泛型 ICloneable.Clone() 将泛型 ICloneable&lt;A&gt;.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()不必检查对象是否为B类型)。

【讨论】:

    猜你喜欢
    • 2011-01-20
    • 2015-03-24
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    相关资源
    最近更新 更多