【发布时间】:2009-11-04 21:58:01
【问题描述】:
是否可以在紧凑框架中深度克隆对象?我希望使用 IClonable 和 memberwiseclone() 但这只会执行浅拷贝。
关于如何使用 C# 2.0 做到这一点的任何想法?
非常感谢,
莫里斯
【问题讨论】:
标签: c# windows-mobile compact-framework clone
是否可以在紧凑框架中深度克隆对象?我希望使用 IClonable 和 memberwiseclone() 但这只会执行浅拷贝。
关于如何使用 C# 2.0 做到这一点的任何想法?
非常感谢,
莫里斯
【问题讨论】:
标签: c# windows-mobile compact-framework clone
我通过使我的对象可序列化[Serializable()] 并使用以下方法实现了深层对象复制。
public static ObjectType CopyObject<ObjectType>(ObjectType oObject)
{
XmlSerializer oSeializer = null;
// Creates the serializer
oSeializer = new XmlSerializer(oObject.GetType());
//Use the stream
using (MemoryStream oStream = new MemoryStream())
{
// Serialize the object
oSeializer.Serialize(oStream, oObject);
// Set the strem position
oStream.Position = 0;
// Return the object
return (ObjectType)oSeializer.Deserialize(oStream);
}
}
【讨论】: