编程语言
首页 > 编程语言> > c#-与XML反序列化IEnumerable类有关的错误

c#-与XML反序列化IEnumerable类有关的错误

作者:互联网

我正在尝试将HistoryRoot类序列化和取消序列化为这种XML格式:

<?xml version="1.0"?>
<HistoryRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Files>
    <HistoryItem d="2015-06-21T17:40:42" s="file:///D:\cars.txt" />
  </Files>
  <Folders>
    <HistoryItem d="2015-06-21T17:40:42" s="D:\fc\Cars" />
  </Folders>
</HistoryRoot>

这是HistoryRoot,HistoryList和HistoryItem类:

[Serializable]
public class HistoryRoot
{
    public HistoryList
    Files = new HistoryList
    {
        sl = new SortedList<DateTime, string>(),
        list = new List<HistoryItem>(),
        max = 500,
        c = program.M.qFile
    },
    Folders = new HistoryList
    {
        sl = new SortedList<DateTime, string>(),
        list = new List<HistoryItem>(),
        max = 100,
        c = program.M.qFolder
    },
}

[Serializable]
public class HistoryList : IEnumerable
{
    [XmlIgnore]
    public List<HistoryItem> list;

    [XmlIgnore]
    public SortedList<DateTime, string> sl;

    [XmlIgnore]
    public int max;

    [XmlIgnore]
    public ComboBox c;

    public IEnumerator GetEnumerator()
    {
        if (list == null) list = new List<HistoryItem>();
        return list.GetEnumerator();
    }
}

public struct HistoryItem
{
    [XmlAttribute("d")]
    public DateTime D;

    [XmlAttribute("s")]
    public string S;
}

这是我得到错误的地方:

using (FileStream fs = new FileStream("filepath.xml", FileMode.Open))
    {
        XmlSerializer serializer = new XmlSerializer(typeof(HistoryRoot));
        HistoryRoot h = (HistoryRoot)serializer.Deserialize(fs);
    }

“出现错误,反映了’History.HistoryRoot’类型.” System.Exception {System.InvalidOperationException}
如何解决此错误?谢谢!

解决方法:

为了序列化或反序列化使用XmlSerializer实现IEnumerable的类,您的类必须具有Add方法.从documentation

The XmlSerializer gives special treatment to classes that implement IEnumerable or ICollection. A class that implements IEnumerable must implement a public Add method that takes a single parameter. The Add method’s parameter must be of the same type as is returned from the Current property on the value returned from GetEnumerator, or one of that type’s bases.

即使您从不反序列化也仅进行序列化,也必须具有此方法,因为XmlSerializer会同时为序列化和反序列化生成运行时代码.

该方法实际上并不需要成功进行序列化,只需要存在即可:

    public void Add(object obj)
    {
        throw new NotImplementedException();
    }

(当然,要使反序列化成功,必须实现该方法.)

标签:xml-deserialization,xml-serialization,xml,c
来源: https://codeday.me/bug/20191120/2041585.html