如何在没有无参数构造函数的情况下对密封类进行 XML 序列化?
我目前正在使用 XMLSerializer
来序列化我自己的类的列表。该类的属性之一是密封类的实例,该类没有无参数构造函数,因此 XML 序列化程序拒绝序列化该类。我该如何解决这个问题?我需要将该属性序列化。
有什么方法可以让我指定该类应该如何序列化吗?
我们希望继续使用 XML;我可以使用另一个不会出现此问题的 XML 序列化程序吗?
再次,如果这是一个骗局,我深表歉意,但我不知道要搜索什么。
[编辑] 澄清一下,我无权访问密封类的源代码。
I'm currently using an XMLSerializer
to serialize a list of a class of my own. One of the class's properties is an instance of a sealed class that does not have a parameterless constructor, so the XML Serializer refuses to serialize the class. How can I get around this? I need that property to be serialized.
Is there some way for me to specify how that class should be serialized?
We'd like to stay with XML; is there another XML serializer that I could use that would not have this problem?
Again, I apologize if this is a dupe, but I had no idea what to search.
[EDIT] To clarify, I don't have access to the source of the sealed class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
直接做是不可能的;
XmlSerializer
无法处理没有无参数构造函数的类。我通常所做的是将无参数类包装在另一个与 XML 兼容的类中。包装类有一个无参数构造函数和一组读写属性;它有一个
FromXml
方法来调用真实类的构造函数。It's not possible to do directly;
XmlSerializer
can't cope with classes that don't have a parameterless constructor.What I normally do is wrap the parameterless class in another class that's compatible with XML. The wrapper class has a parameterless constructor and a set of read-write properties; it has a
FromXml
method that calls the real class's constructor.你能创建一个私有的无参数构造函数吗?假设您可以访问该类的代码,那么这将起作用。
Can you make a private parameterless constructor? That will work assuming you have access to the class's code.
您可以在包含的类上实现
ISerialized
,然后实现自定义序列化程序。You can implement
ISerializable
on the containing class, then implement a custom serializer.根据 xml 的复杂性,您可能可以使用
DataContractSerializer
。这不提供任何类似相同级别的 xml 控制,但它完全绕过构造函数。并且适用于私人类型。我可能还会问:它真的需要是xml吗?还有其他序列化程序,例如 json 或 protobuf,它们没有
XmlSerializer
限制。Depending on the complexity of the xml, you might have some luck with
DataContractSerializer
. This doesn't offer anything like the same level of xml control, but it bypasses the constructor completely. And works for private types.I might also ask: does it actually need to be xml? There are other serializers for things like json or protobuf that don't have the
XmlSerializer
limitations.使用
IXmlSerialized
,XmlSerializer
的局限性太大。Use
IXmlSerializable
,XmlSerializer
is too limited.