为什么字典对象不能在C#中被XmlSerialized? [英] Why can't a dictionary object be XmlSerialized in C#?

查看:137
本文介绍了为什么字典对象不能在C#中被XmlSerialized?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎序列化非常简单。假设键和值都是可序列化的,那么可以比在XML中表示键值对更简单?

It seems that serialization is very straightforward. Assuming that both the key and value are serializable, what could be simpler than representing key-value pairs in XML?!

对所有的评论者:首先,我很感激你的答案,但是我对workoraunds的兴趣较少(在网页上确实有大量的SerializableDictionary实现拣选),更多关于这个设计决策的原因。

To all the commenters: First of all, I appreciate your answers, But- I am less interested in workoraunds (There is indeed plenty of SerializableDictionary implementations on the web for picking) and more as to the reason for this design decision.

推荐答案

为什么部分:


不幸的是没有办法使用IDictionary派生对象使XmlSerializer功能,因为基础架构在运行时显式检查IDictionary并禁用序列化。这样做的一个方法是编写一个包含IDictionary对象的新类,并将值复制到可序列化对象的数组中。 XmlSerializer框架还具有编写自定义序列化代码的隐藏钩子。为了利用这个钩子,您可以为要序列化/反序列化的对象实现一个名为IXmlSerializable的接口。

Unfortunately there's no way to make XmlSerializer function with IDictionary-derived objects since the infrastructure explicitly checks for IDictionary at run time and disables serialization. One way around this is to write a new class that wraps an IDictionary object and copies the values into an array of serializable objects. The XmlSerializer framework also has a hidden hook for writing custom serialization code. To take advantage of this hook you can implement an interface called IXmlSerializable for the object you want to serialize/deserialize.

当您实例化一个XmlSerializer对象时,构造函数通常会生成一个包含用于在对象实例和XML文档之间移动的XmlReader和XmlWriter代码的临时程序集。然而,在执行此操作之前,它首先检查所提供的类型是否来自IXmlSerializable,如果是,则会生成代码以调用IXmlSerializable成员。换句话说,如果你实现IXmlSerializable,你完全绕过自动序列化过程,并有机会提供自己的。

When you instantiate an XmlSerializer object, the constructor usually generates a temporary assembly containing XmlReader and XmlWriter code for moving between object instances and XML documents. Before doing this, however, it first checks to see if the supplied type derives from IXmlSerializable and if so, it generates code to call into the IXmlSerializable members instead. In other words, if you implement IXmlSerializable, you completely bypass the automatic serialization process and have the opportunity to provide your own.

你可以阅读整篇文章: XML文件:高级类型映射

You can read entire article here: XML Files: Advanced Type Mappings

这篇关于为什么字典对象不能在C#中被XmlSerialized?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆