首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OrderedDictionary深拷贝

OrderedDictionary深拷贝
EN

Stack Overflow用户
提问于 2013-09-18 13:08:55
回答 3查看 1.7K关注 0票数 0

创建OrderedDictionary深度副本的最简单方法是什么?我试着做了一个这样的新变量:

代码语言:javascript
复制
var copy = dict[x] as OrderedDictionary;

但是,如果我更新复制中的值/键,则右键中的字典也会被更新。

编辑: dict是另一个OrderedDictionary。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-09-18 13:32:39

您应该能够使用通用的深度克隆方法。msdn杂志深度克隆的一个例子:

代码语言:javascript
复制
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));
}
票数 2
EN

Stack Overflow用户

发布于 2013-09-18 13:14:41

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

您需要迭代字典的内容,并以某种方式克隆/复制内容。

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

代码语言:javascript
复制
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);
}
票数 0
EN

Stack Overflow用户

发布于 2013-09-18 13:22:27

我从你的问题上看不出dict是否是一本字典?创建集合的深层副本的最简单方法是遍历其成员并克隆每个成员。

如果您的值实现了ICloneable:

代码语言:javascript
复制
OrderedDictionary newDict = new OrderedDictionary();
foreach(DictionaryEntry entry in OriginalDictionary)
{
     newDict[entry.Key] = entry.Value.Clone();
}

如果您的值不能是Clone()d,则必须以另一种方式复制它们。

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18873152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档