c# - 如何正确继承克隆方法?

标签 c# inheritance overriding 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 克隆方法?

最佳答案

我找到了一个更好的解决方法:传递通用 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() 不必检查对象是否属于 B 类型)。

关于c# - 如何正确继承克隆方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51737027/

相关文章:

c# - 如何在恰好午夜时在 Datagridview 单元格中显示完整的 DateTime 值?

c# - 类型成员的表达式导致不同的表达式(MemberExpression、UnaryExpression)

java - 有没有办法在java中用父对象实例化子类?

c# - 继承和访问修饰符

python - Python中将对象从类转换为子类的方法

java - 处理一组被覆盖的方法取决于它是任意的还是交替的

c# - ASP.NET Core 2.0+ 中的 Multi-Tenancy

c# - 为什么在不使用 async/await 的情况下使用 Dapper QueryAsync<T> 时抛出 TaskCanceledException?

java - 为什么需要覆盖对象的克隆方法

java - 覆盖父类(super class)的 protected 方法