假设我有一个A类和一个从A派生的B
class A : ICloneable
{
public object Clone() {...}
}
class B : A, ICloneable
{
public object Clone() {...}
}这给了我们
'B.Clone()' hides inherited member 'A.Clone()'. Use the new keyword if hiding was intended.警告。
(1)建议的方式是什么?使用new或将A.Clone()声明为B中的virtual和override
(2)如果在A中有一些成员,并在A.Clone()中正确克隆,有没有简单的方法在B.Clone()中克隆他们,或者我也必须显式地在B.Clone()中克隆他们?
发布于 2013-01-01 00:16:27
如果您有权访问源代码(我猜这里就是这种情况),那么一定要将其声明为virtual并覆盖它。如果用new隐藏基本Clone可能不是一个好主意。如果任何代码不知道它正在使用克隆,那么它将触发错误的B方法,并且不会返回正确的克隆。
关于属性的分配,也许可以考虑实现复制构造函数,每个级别都可以处理自己的克隆:
public class A : ICloneable
{
public int PropertyA { get; private set; }
public A()
{
}
protected A(A copy)
{
this.PropertyA = copy.PropertyA;
}
public virtual object Clone()
{
return new A(this);
}
}
public class B : A, ICloneable
{
public int PropertyB { get; private set; }
public B()
{
}
protected B(B copy)
: base(copy)
{
this.PropertyB = this.PropertyB;
}
public override object Clone()
{
return new B(this);
}
}每个复制构造函数都会调用基本复制构造函数,并将自身向下传递。每个继承级别都会直接复制属于它的属性。
编辑:如果使用new关键字隐藏基本实现,下面是可能发生的情况的示例。使用一个示例实现(从表面上看,这看起来很好)
public class A : ICloneable
{
public int PropertyA { get; protected set; }
public object Clone()
{
Console.WriteLine("Clone A called");
A copy = new A();
copy.PropertyA = this.PropertyA;
return copy;
}
}
public class B : A, ICloneable
{
public int PropertyB { get; protected set; }
public new object Clone()
{
Console.WriteLine("Clone B called");
B copy = new B();
copy.PropertyA = this.PropertyA;
copy.PropertyB = this.PropertyB;
return copy;
}
}但是当你使用它的时候:
B b = new B();
A a = b;
B bCopy = (B)a.Clone();
//"Clone A called" Throws InvalidCastException! We have an A!https://stackoverflow.com/questions/14103693
复制相似问题