作为List属性的XML数组反序列化失败

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (223)

我正在尝试序列化/反序列化具有ConcurrentBag类型字段的类。

这是我的方法:

public class XmlSerializable
{
    [XmlIgnore]
    public ConcurrentBag<string> Array = new ConcurrentBag<string>();
    [XmlElement(ElementName = "Array")]
    public List<string> ArrayXml { get { return Array.ToList(); } set { Array = new ConcurrentBag<string>(value); } }
}

当我尝试序列化它时,一切看起来都不错,但是当我尝试反序列化它时,数组是空的。

    XmlSerializable serializable = new XmlSerializable();
    serializable.Array.Add("entry1");

    XmlSerializer xmlSerializer = new XmlSerializer(typeof(XmlSerializable));
    StringWriter stringWriter = new StringWriter();
    XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true });
    xmlSerializer.Serialize(xmlWriter, serializable);
    string xml = stringWriter.ToString();
    Console.WriteLine(xml);

    StringReader stringReader = new StringReader(xml);
    XmlReader xmlReader = XmlReader.Create(stringReader);
    xmlSerializer = new XmlSerializer(typeof(XmlSerializable));

    XmlSerializable deserialized = (XmlSerializable)xmlSerializer.Deserialize(xmlReader);
    Console.WriteLine(deserialized.Array.Count);

这是片段输出:

<?xml version="1.0" encoding="utf-16"?>
<XmlSerializable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Array>entry1</Array>
</XmlSerializable>
0

如您所见,序列化有效,但在反序列化时,数组为空。

提问于
用户回答回答于

当类定义如下时,看起来工作正常:

public class XmlSerializable
{
    [XmlIgnore]
    public ConcurrentBag<string> Array = new ConcurrentBag<string>();
    [XmlElement(ElementName = "Array")]
    public string[] ArrayXml { get { return Array.ToArray(); } set { Array = new ConcurrentBag<string>(value); } }
}

该属性必须是string[]而不是List<string>。虽然奇怪,因为它适用于类型的字段List<T>,但显然不具有类型的属性List<T>

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励