c# - XmlSerializer 没有序列化我的类中的所有内容

标签 c# list xml-serialization ienumerable xmlserializer

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

[Serializable]
public class ProductCollection : List<Product>
{
    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()时我得到以下信息:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfProduct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Product>
    <InputType>1</InputType>
  </Product>
  <Product>
    <InputType>1</InputType>
  </Product>
</ArrayOfProduct>

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

我做错了什么吗?怎么了??

更新感谢您的回复。我不知道这是设计使然。我已转换为 BinaryFormatter(用于二进制序列化),并且效果非常好。

最佳答案

已关注 msdn :

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

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

关于c# - XmlSerializer 没有序列化我的类中的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1797947/

相关文章:

c# - C# 中的 IXmlSerialized 字典没有 'Key'/'Value' 节点

c# - 使用 XML 序列化将属性放入不同的 XML 命名空间

c# - 使用 c# 以编程方式读取 Openoffice Calc (.ods)?

C# 谷歌翻译,不带 api 且带 unicode

list - 如何修改列表中的结构项?

python - 如何返回给定长度的所有列表元素?

java - 为什么我的列表没有在 JAXB 中序列化?

c# - 具有较大最大值的 System.Windows.Forms.TrackBar 内存使用

c# - 如何让 Gecko 在每个实例中使用单独的 CookieContainer?

java - 添加到空列表