C# 如何正确继承克隆方法?
我有一个基类(C# 如何正确继承克隆方法?,c#,inheritance,overriding,clone,cloning,C#,Inheritance,Overriding,Clone,Cloning,我有一个基类(a)和一个已交付的类(B)。它们继承了我制作的ICloneable通用接口: interface ICloneable<T> { T Clone(); } (我还添加了非泛型ICloneable的显式实现,但在示例中没有显示。) 有没有更好的方法来实现这一点,而不必使用错误的克隆方法?我发现了一个更好的解决方法:使用非泛型的ICloneable.clone()方法将泛型ICloneable.clone()方法的调用向下传递到继承层次结构,可能会很有用,如下所示
a
)和一个已交付的类(B
)。它们继承了我制作的ICloneable
通用接口:
interface ICloneable<T>
{
T Clone();
}
(我还添加了非泛型ICloneable
的显式实现,但在示例中没有显示。)
有没有更好的方法来实现这一点,而不必使用错误的克隆方法?我发现了一个更好的解决方法:使用非泛型的
ICloneable.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类:可克隆,可克隆
{
A Clone()=>(A)((ICloneable)this.Clone();//如果对象的类型为B,则将调用类B中的ICloneable.Clone!
//如果对象的类型为B,则调用的不是此类型,而是派生方法:
对象iclonable.Clone()=>/*克隆,如果对象是*/的实例;
}
B类:A类,可克隆
{
new B Clone()=>(B)((ICloneable)this.Clone();//如果对象的派生类型更多,则将在派生类型中调用ICloneable.Clone!
//如果对象的派生类型更多,则调用派生类的方法,而不是此方法:
对象ICLOnable.Clone()=>/*克隆,如果对象是B*/的实例;
}
//类C的相同实现。。。
这样做的好处是,所有方法都不必显式检查对象的类型(即在类A
中,Clone()
不必检查对象是否为B
)类型。c#还不支持这一点。你的变通方法是丑陋的,因为你仍然强迫自己这么做。实现这一点的更好方法是不使用ICloneable接口,让每个类都有自己的克隆方法,而不使用虚拟/重写。
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...