I have structure like this:
public interface A
{
public void method();
}
public class B : A
{
}
public class C : A
{
}
List<A> list;
List contains objects of type B and C they also have some fields that I would like to keep, can I now serialize it, deserialize back and get the proper object instances? Preferably to XML
EDIT:
Is there any simple way to serialize this list that contains interfaces, and then deserialize it back to B and C instances?
I would use an abstract class instead of an interface (as one cannot serialize a type of interface), then instead of hard coding the type using the XmlInclude attribute, I would add the known types to the XmlSerializer in the Serial and Deserialize methods like so:
For your case make an abstract class that implements your interface like:
and then derive your classes from Abs
and List list;
now use XmlIncludeAttribute to add your types into the XmlSerializer's type array.
XmlSerializer
does not work with interfaces. So you can:Convert interface to abstract class and then use
XmlIncludeAttribute
for it or provide KnownTypes toXmlSerializer
or
Implement
IXmlSerializable
for the parent typeor
Consider using
DataContractSerializer
from .NET 3.0You may try using DataContractSerializer:
Yes, but you have to play with the XmlElement, XmlRoot and XmlArray Attributes. Each Type needs it's own element name.
EDIT: Some sample code. All classes are derived from a common base class.
Here is a sample code:
EDIT: Remove Serialization Attribute as it's not needed (but is needed in my project where the code is from)
Assuming you're using the built in .net XML serialization you should take a look at the following attribute:
It allows you to instruct the serializer to include other types when serializing/deserializing.
Adding new types to the list and not updating the serialization meta data is a common source of mistakes, make sure you have adequate test coverage.