问题
(Havent spotted a question asking this).
Why cant a Dictionary be serialized?
Most resources, websites, blogs etc say that it cannot be serialized. However reading "CLR via C#" 3rd edition, page 664 gives Dictionary as an example of an object graph which can be serialized.
Note that this chapter talks about Binary Serialization. So is it that it can be serialized using the BinaryFormatter but it cannot be XML serialized?
Or is there some difference here that Im missing between an IDictionary and a Dictionary?
To clarify... under what circumstances can a Dictionary be serialized and under what circumstances can it not be serialized.
Thanks.
回答1:
I think this is just a limitation of Microsoft's XML serializer (System.Xml.Serialization.XmlSerializer
). Most other serializers will support dictionaries.
This is not a general limitation of serialization, not even xml serialization, just a limitation of that implementation. XmlSerializer
is pretty weak in general.
回答2:
Here is the reason why it is so:
Objects are reconstructed from the inside out, and calling methods during deserialization can have undesirable side effects, since the methods called might refer to object references that have not been deserialized by the time the call is made. If the class being deserialized implements the IDeserializationCallback, the OnSerialization method will automatically be called when the entire object graph has been deserialized. At this point, all the child objects referenced have been fully restored. A hash table is a typical example of a class that is difficult to deserialize without using the event listener described above. It is easy to retrieve the key/value pairs during deserialization, but adding these objects back to the hash table can cause problems since there is no guarantee that classes that derived from the hash table have been deserialized. Calling methods on a hash table at this stage is therefore not advisable.
来源:https://stackoverflow.com/questions/8342719/why-cant-a-dictionarykey-value-be-serialized-or-can-it