how can i serialize this class?
public class MyClass {
IInterface MyProperty开发者_运维百科 { get; set;}
}
You need to add a setter to MyProperty as Xml serialization rules mandate that serialization must be able to round-trip i.e. it must be able to get the property for serialization, then set the property for deserialization.
As chibacity said, you need to add a setter to the property. You also need to add the XmlInclude
attribute to the property to specify the possible implementing types, otherwise the XmlSerializer
won't know what type to instantiate when deserializing
The XmlSerializer cannot serialize interfaces.
If you know the concrete types you will be dealing with in advance then you can use the XmlInclude
approach. If not then there have been a few discussions about how to handle this:
- XML serialization of interface property
- XmlSerialization with Interfaces
- Serializing without XmlInclude
Make the class that implements IInterface Serializable like you normally would and it will all work.
精彩评论