简体   繁体   English

C#解决XmlSerializer.Deserialize陷阱?

[英]C# work around for XmlSerializer.Deserialize pitfall?

I was just wondering if there are any good work-arounds for Deserializing private fields/properties using XmlSerializer.Deserialize() ? 我只是想知道是否存在使用XmlSerializer.Deserialize()反序列化私有字段/属性的良好解决方法?

Currently, I Deserialize my XML to a simple disposable type with all public properties, then I load the complex type that has private properties like this: 当前,我将XML反序列化为具有所有公共属性的简单的一次性类型,然后加载具有私有属性的复杂类型,如下所示:

ComplexType complex = new ComplexType(SimpleType);

and the constructor of ComplexType looks like this: 而ComplexType的构造函数如下所示:

public ComplexType(SimpleType simpleType){
    this.Property1 = simpleType.Property1;
    this.Property2 = simpleType.Property2;
    .....

}

Anyone has a better way of doing this? 有人有更好的方法吗?

You can have ComplexType implement the IXmlSerializable interface. 您可以使ComplexType实现IXmlSerializable接口。 This exposes methods for serialization and deserialization, so you can fill the private members of complextype in these methods. 这公开了用于序列化和反序列化的方法,因此您可以在这些方法中填充复杂类型的私有成员。

Check out MSDN here: http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx for an example showing an implementation of the IXmlSerializable interface that serializes a private field. 在此处出MSDN: http : //msdn.microsoft.com/zh-cn/library/system.xml.serialization.ixmlserializable.aspx ,该示例显示了对序列化私有字段的IXmlSerializable接口的实现。

请注意,另一个选择是使用DataContractSerializer (.NET 3.0)-这支持私有成员(属性或字段)的序列化。

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

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