如何将XML与它的基类序列化子类它的、子类、如何将、序列化

2023-09-04 00:41:55 作者:汐颜°

我能够序列化的单一类型/班,但没有办法,我可以序列化的方式基类呢?

I am able to serialize a single type/class but is there a way that I can serialize it base class too?

例如:

class B:A

在这里,我能B级序列化,但我怎么可以序列A类?

Here I am able to serialize class B but how can I serialize class A ?

推荐答案

A 必须事先了解,比如

[XmlInclude(typeof(B))]
public class A {...}


public class B {...}

现在一个新的XmlSerializer(typeof运算(A))可序列化 A B 。您也可以做到这一点的没有的属性通过传递 extraTypes 参数重载的XmlSerializer 构造函数,但同样 - 根应 A ;即新XmlSeralializer(typeof运算(A),新的[] {typeof运算(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)})