Serializing dictionary in XNA 4.0
I want to serialize a tree in XNA 4.0, where each node has the children node in a member dictionary indexed by int as such:
[Serializable]
public class Node
{
private Dictionary<int, Node> children;
}
My intention is that when I serialize a specific node, all the sub-tree that has that node as root gets serialized. But when I try to test it out, it seems to have a problem serializin开发者_开发技巧g the dictionary, it replies with the error (simplified):
System.InvalidOperationException was unhandled
Message=There was an error reflecting type 'Baddies.Node.Node'.
InnerException: System.NotSupportedException
Message=Cannot serialize member Baddies.Nodes.Node.Children of type System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[Baddies.Nodes.Node, Baddies, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], because it implements IDictionary.
My question is a double one. First, if the class Dictionary was serializable, would this do what I expect it to do? (that is, serialize all the sub-tree). Second, how do I go about serializing the dictionary class then?
Any and all information welcome. Thank you for your time.
It appears that types that implement IDictionary cannot be serialized out of the box using XmlSerializer.
Read here on how to solve this: XML Serialize IDictionary types (Hashtable, DictionaryBase etc)
精彩评论