How can I make a deep-copy of a read only OrderedD

2019-09-04 13:57发布

问题:

The orderedDictionary instantiation is this:

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

orderedDictionary is read only.

How can I make a deep copy of orderedDictionary that is not read only? Serialization/deserialization doesn't work cause it also copies the read only part.

回答1:

The easiest way would be to just copy the objects:

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

UPDATE:
This code will NOT create a deep copy of the values in the dictionary.
Example:

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);
}

Both dictionary will contain one entry with the key "1" and the same list. Removing an item from this list in any of the dictionaries will also change the contents of the list in the other dictionary, because there only IS one list.

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);

This will output the following:

2
2
True
1
1

Assigning a new value to a key in one of the dictionary however has no effect on the other dictionary:

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);

This will output:

False
2
3