I am able to serialize a single type/class but is there a way that I can serialize it base class too?
For example:
class B:A
Here I am able to serialize class B but h开发者_运维百科ow can I serialize class A ?
A
must know in advance, i.e.
[XmlInclude(typeof(B))]
public class A {...}
public class B {...}
Now a new XmlSerializer(typeof(A))
can serialize an A
or a B
. You can also do this without attributes by passing in a extraTypes
parameter to the overloaded XmlSerializer
constructor, but again - the root should be A
; i.e. new XmlSeralializer(typeof(A), new[] {typeof(B)})
Your question is very vague.
You could just cast your object to the base class when serializing, however when you do that you need to provide the sub-types that A can assume when creating a serializer (new XmlSerializer(typeof(MyClass), ExtraTypesGoHere);
), or you use [XmlInclude(Type type)]
in the classes that may have properties exposing objects of those sub-types.
精彩评论