首页 / 问答 / 解惑,请教C#&.NET带字典的对象不能深拷贝的问题?

解惑,请教C#&.NET带字典的对象不能深拷贝的问题?

.NET C# Dictionary 序列化 字典 1.04K 次浏览
0

在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应用程序中,如何实现深拷贝包含字典类型的对象呢?

回复 [×]
提交评论
请输入评论内容

2 个回答

  • 1

    这里提供一个可以深拷贝字典的示例:

    运行结果:

    ObjectExtensions.cs类和相关的静态扩展方法如下:

    Rector的个人主页

    Rector

    2022-11-08 回答

    • 0

      另一种可选方案是使用BinaryFormatter类,但BinaryFormatter类已经被微软官方弃用。

      实现示例代码如下:

      Rector的个人主页

      Rector

      2022-11-08 回答

      我来回答