简体   繁体   中英

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() ?

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:

ComplexType complex = new ComplexType(SimpleType);

and the constructor of ComplexType looks like this:

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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