【问题标题】:How can I make a deep-copy of a read only OrderedDictionary with keys and values being strings that is no longer read only?如何制作只读 OrderedDictionary 的深层副本,其中键和值是不再只读的字符串?
【发布时间】:2011-10-01 02:31:57
【问题描述】:

orderedDictionary 实例化是这样的:

IOrderedDictionary orderedDictionary= gridview.DataKeys[index].Values;

orderedDictionary 是只读的。

如何制作非只读的orderedDictionary 的深层副本?序列化/反序列化不起作用,因为它还会复制只读部分。

【问题讨论】:

标签: c# deep-copy readonly ordereddictionary


【解决方案1】:

最简单的方法是复制对象:

var newDictionary = new OrderedDictionary();
foreach(DictionaryEntry de in orderedDictionary)
{
    newDictionary.Add(de.Key, de.Value);
}

更新:
此代码不会创建字典中值的深层副本。
示例:

var orderedDictionary = new OrderedDictionary();
orderedDictionary.Add("1", new List<int> { 1, 2 });

var newDictionary = new OrderedDictionary();
foreach(DictionaryEntry de in orderedDictionary)
{
    newDictionary.Add(de.Key, de.Value);
}

两个字典都将包含一个带有键“1”的条目和相同的列表。从任何字典中的该列表中删除一个项目也会改变另一个字典中列表的内容,因为只有一个列表。

Console.WriteLine(((List<int>)orderedDictionary["1"]).Count);
Console.WriteLine(((List<int>)newDictionary["1"]).Count);
Console.WriteLine(ReferenceEquals(orderedDictionary["1"], newDictionary["1"]));
((List<int>)orderedDictionary["1"]).Remove(1);
Console.WriteLine(((List<int>)orderedDictionary["1"]).Count);
Console.WriteLine(((List<int>)newDictionary["1"]).Count);

这将输出以下内容:

2
2
True
1
1

为其中一个字典中的键分配新值但对另一个字典没有影响:

newDictionary["1"] = new List<int>{3,4};
Console.WriteLine(ReferenceEquals(orderedDictionary["1"], newDictionary["1"]));
Console.WriteLine(((List<int>)orderedDictionary["1"]).Count);
Console.WriteLine(((List<int>)newDictionary["1"]).Count);

这将输出:

False
2
3

【讨论】:

  • 正是我的想法,但是,这只是将引用从一本字典复制到另一本字典吗?那会是“深”吗?
  • @Jodrell:你说得对,这不是深拷贝。尽管 OP 要求进行深度复制,但我认为他并不想这样做。我这样读了他的问题,他只是想创建一个新的OrderedDictionary,它不是只读的。不过,我可能错了。
  • @Daniel Hilgarth:您的解决方案很好,它对orderedDictionary 进行了深层复制,我对其进行了测试,修改newDictionary 值不会影响orderedDicionary 值。谢谢!
  • @Jodrell,@Daniel Higarth,似乎有几个深度。 :-)
  • @Răzvan:这不是真正的深拷贝。修改其中一个词典中某个项目的属性将导致另一个词典中相同项目的属性发生变化,因为它们实际上是相同的。换句话说:您有两个不同的字典,但这些字典中的对象是相同的。
猜你喜欢
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多