我有一个基类 ( 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/