我在克隆对象层次结构时遇到一些问题。它是一个用于建模应用程序的工具包,该工具箱包含作为原型的类实例。但我很难克隆这些:)
下面的代码显示了这个问题:
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
and MemoryStreams
).
第一种方法缺乏调用方法base.clone()
方法(或者我错了?),后者不起作用,因为UIElement
不是[Serializable]
.
注意:必须是深拷贝!
有任何想法吗?谢谢!
UPDATE
只是为了澄清我的手动克隆方法:
如果每个班级都有自己的班级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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)