在 XNA 4.0 中序列化字典
我想在 XNA 4.0 中序列化一棵树,其中每个节点在成员字典中都有由 int 索引的子节点,如下所示:
[Serializable]
public class Node
{
private Dictionary<int, Node> children;
}
我的意图是,当我序列化特定节点时,以该节点为根的所有子树都会得到连载了。 但是当我尝试测试它时,序列化字典似乎有问题,它回复错误(简化):
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.
我的问题是双重问题。首先,如果类 Dictionary 是可序列化的,这会达到我期望的效果吗? (即序列化所有子树)。其次,我该如何序列化字典类呢?
欢迎任何和所有信息。感谢您抽出时间。
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 serializing 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来实现 IDictionary 的类型无法使用 XmlSerializer 进行开箱即用的序列化。
请阅读此处了解如何解决此问题: XML 序列化 IDictionary 类型(Hashtable、字典库等)
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)