0

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

var copy = dict[x] as OrderedDictionary;

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

编辑:dict 是另一个 OrderedDictionary。

4

3 回答 3

2

您应该能够使用通用的深度克隆方法。来自 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));
}
于 2013-09-18T13:32:39.660 回答
0

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

您需要遍历 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);
}
于 2013-09-18T13:14:41.087 回答
0

我无法从您的问题中判断是否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;
}
于 2013-09-18T13:22:27.093 回答