我在克隆对象层次结构时遇到了一些问题。它是一个用于建模应用程序的工具包,该工具箱包含作为原型(prototype)的类实例。但是我很难克隆这些 :)
以下代码显示了问题:
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()
方法的方法(或者我错了吗?),后者不起作用,因为 UIElement
不是t [可序列化]
。
注意:必须是深拷贝!
有什么想法吗?谢谢!
更新
只是为了阐明我的手动克隆方法:
如果每个类都有自己的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!
}
}
最佳答案
这里是它的函数:
public T XamlClone<T>(T source)
{
string savedObject = System.Windows.Markup.XamlWriter.Save(source);
// Load the XamlObject
StringReader stringReader = new StringReader(savedObject);
System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader);
T target = (T)System.Windows.Markup.XamlReader.Load(xmlReader);
return target;
}
关于c# - 克隆 WPF 控件和对象层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6766787/