c# – 在派生类中可克隆
发布时间:2020-12-16 01:52:16 所属栏目:百科 来源:网络整理
导读:假设我有一个A类和B类,它来自A: 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
假设我有一个A类和B类,它来自A:
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)建议的方式是什么?使用新的或声明A.Clone()作为虚拟和覆盖B? (2)如果A中有一些成员并且在A.Clone()中正确克隆,是否有一种简单的方法可以在B.Clone()中克隆它们,还是必须在B.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! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |