开发者

How to XML serialize child class with its base class

开发者 https://www.devze.com 2023-02-09 23:47 出处:网络
I am able to serialize a single type/class but is there a way that I can serialize it base class too?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号