【问题标题】:Deep Copy of OrderedDictionaryOrderedDictionary 的深拷贝
【发布时间】:2013-09-18 13:08:55
【问题描述】:

创建 OrderedDictionary 的深层副本的最简单方法是什么?我尝试像这样创建一个新变量:

var copy = dict[x] as OrderedDictionary;

但如果我更新副本中的值/键,dict[x] 中的字典也会更新。

编辑:dict 是另一个 OrderedDictionary。

【问题讨论】:

  • 请贴出dict变量的定义。
  • 最简单的方法大概是对OrderedDictionary进行序列化和反序列化。
  • @JonLaMarr 该答案实际上并没有创建深层副本(阅读 cmets 到答案)。

标签: c#


【解决方案1】:

您应该能够使用通用深度克隆方法。来自 msdn 杂志的深度克隆示例:

Object DeepClone(Object original)
{
    // Construct a temporary memory stream
    MemoryStream stream = new MemoryStream();

    // Construct a serialization formatter that does all the hard work
    BinaryFormatter formatter = new BinaryFormatter();

    // This line is explained in the "Streaming Contexts" section
    formatter.Context = new StreamingContext(StreamingContextStates.Clone);

    // Serialize the object graph into the memory stream
    formatter.Serialize(stream, original);

    // Seek back to the start of the memory stream before deserializing
    stream.Position = 0;

    // Deserialize the graph into a new set of objects
    // and return the root of the graph (deep copy) to the caller
    return (formatter.Deserialize(stream));
}

【讨论】:

  • 所有类型都应该是serializable(甚至是封装类型等)才能工作
  • 此外,如果字典中的任何键(或值)包含任何事件,二进制序列化将尝试将事件与整个侦听器一起序列化,这可能会很麻烦。它也不是很快。另请参阅stackoverflow.com/a/11308879/168719
【解决方案2】:

您在字典中存储什么类型的对象?

您需要遍历 Dictionary 的内容并以某种方式克隆/复制内容。

如果你的对象实现了ICloneable,你可以这样做,

Dictionary<int, MyObject> original = new Dictionary<int, MyObject>();
... code to populate original ...

Dictionary<int, MyObject> deepCopy = new Dictionary<int, MyObject>();

foreach(var v in a)
{
    MyObject clone = v.Value.Clone();
    b.Add(v.Key, clone);
}

【讨论】:

  • 我正在存储各种不同的对象,从 DataTables 到 Strings 到 Decimals 到 Integers...
  • ICloneable 用于浅拷贝
  • @SriramSakthivel 不一定。来自msdn.microsoft.com/en-us/library/system.icloneable.aspxICloneable 接口只要求您的 Clone 方法实现返回当前对象实例的副本。它没有指定克隆操作是执行深拷贝、浅拷贝还是介于两者之间。
  • @Stijn 我的错,一般都是浅拷贝实现的。
【解决方案3】:

我无法从您的问题中判断dict 是否是字典?制作集合的深层副本的最简单方法是遍历其成员并克隆每个成员。

如果你的值实现了 ICloneable:

OrderedDictionary newDict = new OrderedDictionary();
foreach(DictionaryEntry entry in OriginalDictionary)
{
     newDict[entry.Key] = entry.Value.Clone();
}

如果你的值不能被 Clone()d,你将不得不以另一种方式复制它们。

OrderedDictionary newDict = new OrderedDictionary();
foreach(DictionaryEntry entry in OriginalDictionary)
{
     MyClass x = new MyClass();
     x.myProp1 = entry.Value.myProp1 as primitive value;
     x.myProp2 = entry.Value.myProp2 as primitive value;
     newDict[entry.Key] = x;
}

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 2015-01-13
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多