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

时间:2019-01-06 23:51:05

标签: c# xml-serialization xmlserializer

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

这是我的方法:

TimeSpan expCount = DateTime.Now - expDate;

当我尝试对其进行序列化时,一切看起来都不错,但是当我尝试对其进行反序列化时,该数组为空。

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);

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

1 个答案:

答案 0 :(得分:1)

当类定义如下时,它似乎可以工作:

<p class="IndieFlower">This is a paragraph.</p>

该属性必须为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>类型的属性。