XmlSerializer不会序列化我class级中的所有内容

我有一个非常基本的类,它是一个子类列表,加上一些摘要数据。

 [Serializable] public class ProductCollection : List { public bool flag { get; set; } public double A { get; set; } public double B { get; set; } public double C { get; set; } } ... // method to save this class private void SaveProductCollection() { // Export case as XML... XmlSerializer xml = new XmlSerializer(typeof(ProductCollection)); StreamWriter sw = new StreamWriter("output.xml"); xml.Serialize(sw, theCollection); sw.Close(); } 

[Serializable] public class ProductCollection : List { public bool flag { get; set; } public double A { get; set; } public double B { get; set; } public double C { get; set; } } ... // method to save this class private void SaveProductCollection() { // Export case as XML... XmlSerializer xml = new XmlSerializer(typeof(ProductCollection)); StreamWriter sw = new StreamWriter("output.xml"); xml.Serialize(sw, theCollection); sw.Close(); }

 [Serializable] public class ProductCollection : List { public bool flag { get; set; } public double A { get; set; } public double B { get; set; } public double C { get; set; } } ... // method to save this class private void SaveProductCollection() { // Export case as XML... XmlSerializer xml = new XmlSerializer(typeof(ProductCollection)); StreamWriter sw = new StreamWriter("output.xml"); xml.Serialize(sw, theCollection); sw.Close(); } 

当我调用SaveProductCollection()我得到以下内容:

    1   1   

请注意,我有基本类型: List 。 但是我没有任何类属性:flag,A,B,C。

我做错什么了吗? 这是怎么回事??

更新感谢您的回复。 我不知道它是按设计的。 我已经转换为BinaryFormatter(用于二进制序列化),它运行得非常好。

以下msdn :

问:为什么集合类的所有属性都没有序列化?

答:XmlSerializer在检测到IEnumerable或ICollection接口时仅序列化集合中的元素。 此行为是设计使然。 唯一的解决方法是将自定义集合重新分解为两个类,其中一个类公开属性,包括一个纯集合类型。

首先,在创建自己的集合类型时,应该inheritanceSystem.Collections.ObjectModel.Collection ,这将允许您重写InsertItem和其他方法以获得对集合的完全控制。

要回答您的问题, XmlSerializer以不同方式处理集合类型以序列化集合中的项目。 它不会序列化任何属性(例如, List.Capacity )。

您可以将属性移动到包含属性或集合的其他类型。

您也可以尝试使用控制XML序列化的属性 ,但我不确定它们是否会有所帮助。

尝试将XmlAttribute添加到属性中,因此它们将被序列化为属性。 就像是:

  [XmlAttribute("flag")] public bool flag { get; set; }