Mat*_*ten 2 c# wpf clone deep-copy
我有一些问题克隆一个对象hierarchie.它是用于建模应用程序的工具包,工具箱包含类实例作为原型.但是我很难克隆这些:)
以下代码显示了问题:
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; }
...
}
Run Code Online (Sandbox Code Playgroud)
当我将一个对象插入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!
}
}
Run Code Online (Sandbox Code Playgroud)
这里有它的功能:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7620 次 |
| 最近记录: |