简体   繁体   English

XMLSerializer的特殊获取器和设置器

[英]Special getters and setters for XMLSerializer

I've got a class which contains a number of resources which are loaded from files. 我有一个包含大量从文件加载的资源的类。 Want to serialize objects of this class to XML but with paths to the resources instead of the actual resources themselves. 想要将此类的对象序列化为XML,但要使用资源路径而不是实际资源本身。

Right now I have got around this by creating a number of ResourceSource fields which store the path to the resource and using XMLIgnore on the resources themselves. 现在,我通过创建许多ResourceSource字段来解决此问题,这些字段存储ResourceSource的路径并在资源本身上使用XMLIgnore However, these have to be public which isn't so good. 但是,这些必须是公开的,效果不是很好。

It would seem that what I really want is to be able to create special property accessors which are only executed by XMLSerialize. 似乎我真正想要的是能够创建仅由XMLSerialize执行的特殊属性访问器。 Does this feature exist or is there a way I might be able to implement it? 此功能是否存在,或者有什么方法可以我实现?

Alternatively, can I set my ResourceSource fields to be accessible only by XMLSerialize? 另外,是否可以将ResourceSource字段设置为只能由XMLSerialize访问?

Have you looked at implementing IXmlSerializable instead? 您是否考虑过实现IXmlSerializable This allows you finer grained control over the serialization process. 这使您可以更好地控制序列化过程。

There are two reasons to implement this interface. 实现此接口有两个原因。 The first is to control how your object is serialized or deserialized by the XmlSerializer. 第一个是控制XmlSerializer如何序列化或反序列化对象。 For example, you can chunk data into bytes instead of buffering large data sets, and also avoid the inflation that occurs when the data is encoded using Base64 encoding. 例如,您可以将数据分块为字节,而不是缓冲大型数据集,并且还可以避免在使用Base64编码对数据进行编码时出现膨胀。 To control the serialization, implement the ReadXml and WriteXml methods to control the XmlReader and XmlWriter classes used to read and write the XML. 要控制序列化,请实现ReadXml和WriteXml方法以控制用于读取和写入XML的XmlReader和XmlWriter类。

The second reason is to be able to control the schema. 第二个原因是能够控制架构。 To enable this, you must apply the XmlSchemaProviderAttribute to the serializable type, and specify the name of the static member that returns the schema. 若要启用此功能,必须将XmlSchemaProviderAttribute应用到可序列化的类型,并指定返回架构的静态成员的名称。

It sounds like your class is being overloaded to have multiple responsibilities, which is almost always a red flag that it's time for some refactoring. 听起来您的班级正在过载以承担多个职责,这几乎总是一个危险信号,该进行一些重构了。

What I would do is have one serializable class that stores the resource paths and another that stores the resources themselves. 我要做的是有一个可序列化的类存储资源路径,另一个可存储类本身的资源。 The constructor for the non-serializable class could take an instance of the serialized class, load the resources from disk, etc. 不可序列化类的构造函数可以采用序列化类的实例,从磁盘加载资源等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM