C# 对IEnumerable类进行XML反序列化时出错

C# 对IEnumerable类进行XML反序列化时出错,c#,xml,xml-serialization,xml-deserialization,C#,Xml,Xml Serialization,Xml Deserialization,我正在尝试将serial和deresial 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:4

我正在尝试将serial和deresial 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>
“反映类型“History.HistoryRoot.”的错误。“System.Exception{System.InvalidOperationException}

如何修复此错误?谢谢!

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

XmlSerializer对实现IEnumerable或ICollection的类给予特殊处理。实现IEnumerable的类必须实现接受单个参数的公共Add方法。Add方法的参数的类型必须与从GetEnumerator返回的值的当前属性返回的类型相同,或者是该类型的基之一

即使从不反序列化而只序列化,也必须使用此方法,因为
XmlSerializer
同时为序列化和反序列化生成运行时代码

该方法实际上不必为序列化成功而工作,它只需要存在:


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

虽然sbc的答案是正确的,我接受了,但我现在将
HistoryList
类更改为更简单:

public class HistoryList : List<HistoryItem> //   <-- Add List<HistoryItem>
{    
    [XmlIgnore]
    public SortedList<DateTime, string> sl;

    [XmlIgnore]
    public int max;

    [XmlIgnore]
    public ComboBox c;
}

谢谢你的帮助,我现在修好了:)
using (FileStream fs = new FileStream("filepath.xml", FileMode.Open))
    {
        XmlSerializer serializer = new XmlSerializer(typeof(HistoryRoot));
        HistoryRoot h = (HistoryRoot)serializer.Deserialize(fs);
    }
    public void Add(object obj)
    {
        throw new NotImplementedException();
    }
public class HistoryList : List<HistoryItem> //   <-- Add List<HistoryItem>
{    
    [XmlIgnore]
    public SortedList<DateTime, string> sl;

    [XmlIgnore]
    public int max;

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