解惑,请教C#&.NET带字典的对象不能深拷贝的问题?
1.53K 次浏览
在C#&.NET应用程序编程开发中,深拷贝一个实例对象的通常做法是序列化拷贝,比如:
public class DeepCopy
{
public static T DeepCopyByBin<T>(T obj)
{
object retval;//序列化深拷贝
using (MemoryStream ms = new MemoryStream()) //创建内存流
{
XmlSerializer bf = new XmlSerializer(typeof(Box));
//序列化成流
bf.Serialize(ms, obj);
//反序列化当前实例到一个object
ms.Seek(0, SeekOrigin.Begin);
retval = bf.Deserialize(ms);
ms.Close();//关闭内存流
}
return (T)retval;
}
}
但对于包含字典类型的对象来说,这种序列化深拷贝的方法会失败,程序抛出异常:
NotSupportedException: Cannot serialize member DemoApp1.Box.Properties of type System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[DemoApp1.Box, DemoApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], because it implements IDictionary.
那么,在C#&.NET应用程序中,如何实现深拷贝包含字典类型的对象呢?