简体   繁体   English

自动为所有派生类提供XmlInclude的方法?

[英]Way to XmlInclude automatically for all derived classes?

Apparently XmlSerializer works smoothly for objects if the instances are not derived, otherwise I'd have to explicitly apply an attribute to include specific derived classes onto the base class. 显然,如果未派生实例,则XmlSerializer可以对对象顺利运行,否则我必须显式地应用属性,以将特定的派生类包括在基类上。 I have around 50+ derived classes and possibly more in the future, is there a way to tell XmlSerializer to just automatically serialize the derived parts of an object and not hassle me to be more explicit with what I want? 我大约有50多个派生类,并且将来可能还会更多,有没有办法告诉XmlSerializer自动序列化对象的派生部分,而又不用麻烦我更清楚地表达我想要的内容? I just want to type less. 我只想少打字。

The need to specify them stems primariliy due to complexities of having to deserialize them. 由于必须对它们进行反序列化的复杂性,因此指定它们的必要性很重要。 At the point of serialization it could, after all, walk the inheritance tree to find information. 毕竟,在序列化时,它可以遍历继承树以查找信息。 But consider being asked to deserialize a Foo , but getting a <bar> it is not immediately obvious how to resolve the type. 但是考虑考虑要求对Foo进行反序列化,但是获得<bar>却不是很明显如何解析类型。

XmlSerializer, sensibly, wants to be sure it can perform both actions - in the same way that it wants a public parameterless constructor before it will serialize, when clearly serialization doesn't call a constructor. 明智的是,XmlSerializer希望确保它可以执行这两种操作-就像在序列化显然不调用构造函数时,它希望在序列化之前使用一个公共的无参数构造函数一样。 So ultimately: no - you are going to have to tell it the types. 所以最终:不-您将不得不告诉它的类型。

Note that this doesn't mean you red to use XmlIncludeAttribute - you can also supply this info the the XmlSerializer constructor (extra types). 请注意,这并不意味着您会使用XmlIncludeAttribute-您还可以将此信息提供给XmlSerializer构造函数(其他类型)。 However, it is IMO more convenient to use the attribute approach, and "typing less" certainly isn't a good reason not to do it that way. 但是,使用属性方法更方便了IMO,并且“少键入”无疑不是一个很好的理由。 Additionally, if using anything other than the XmlSerializer(Type) constructor you need to cache the serializer to prevent leaking assemblies. 此外,如果使用XmlSerializer(Type)构造函数以外的任何东西,则需要缓存序列化程序以防止程序集泄漏。

I'd just add the attributes... 我只是添加属性...

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

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