微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。