【发布时间】:2011-10-09 15:43:42
【问题描述】:
我在克隆对象层次结构时遇到了一些问题。它是一个用于建模应用程序的工具包,该工具箱包含作为原型的类实例。但我很难克隆这些:)
以下代码说明了问题:
public abstract class Shape {
protected List<UIElement> elements;
private Canvas canvas;
...
public Canvas getCanvas() { ... };
}
public class MovableShape : Shape {
protected ... propertyA;
private ... propertyXY;
...
}
public abstract class AbstractLayout : MovableShape, ... {
...
}
public class SomeLayoutClass : AbstractLayout, ... {
...
}
public class AContainingClass {
SomeLayoutClass Layout { get; set; }
...
}
当我将AContainingClass 的对象插入我的项目工作表时,它应该被克隆。到目前为止,我尝试了手动克隆(由于基类中的 private 字段而失败)和二进制序列化(BinaryFormatter 和 MemoryStreams)。
第一种方法缺少调用base.clone() 方法的方法(或者我错了吗?),后者不起作用,因为UIElements 不是[Serializable]。
注意:必须是深拷贝!
有什么想法吗?谢谢!
更新
只是为了澄清我的手动克隆方法:
如果每个类都有自己的Clone方法,如何调用基类的Clone方法?
public class Shape { // not abstract any more
...
public Shape Clone() {
Shape clone = new Shape() { PropertyA = this.PropertyA, ... };
...do some XamlWriter things to clone UIElements...
return clone;
}
}
public class MovableShape : Shape {
...
public MovableShape Clone() {
// how to call base.Clone???
// this would be required because I have no access to the private fields!
}
}
【问题讨论】:
-
那么,手动克隆根本不起作用,还是变得笨拙?私人国家不对应公共国家吗?如果它变得笨拙,我建议使用基于反射的代码生成。否则,是否可以选择复制他们的代码来解决这些缺点?图书馆是开源的吗?如果是这样,您可以提交补丁以使对象可克隆。
-
@Merlyn Morgan-Graham:我为手动克隆添加了一个代码示例