泛型类的xml序列化

时间:2013-06-09 15:56:58

标签: c# .net xml list xml-serialization

我需要将包含Pair<T,U>类型的对象的列表序列化为xml。

首先,我创建了一个类PairList来保存对的列表,然后我创建了实际的类,它代表了一对两个值,key和{{1} }。

value

然后,我尝试将其序列化:

[XmlRoot("pairList")]
public class PairList<T,U> 
{
    [XmlElement("list")]
    public List<Pair<T,U>> list;

    public PairList()
    {
        list = new List<Pair<T, U>>();
    }
}

public class Pair<T, U>
{
    [XmlAttribute("key")]
    public T key;

    [XmlAttribute("value")]
    public U value;

    public Pair(T t, U u)
    {
        key = t;
        value = u;
    }
}

不幸的是我得到了一个例外:PairList<string,int> myList = new PairList<string,int>(); myList.list.Add(new Pair<string, int>("c", 2)); myList.list.Add(new Pair<string, int>("c", 2)); myList.list.Add(new Pair<string, int>("c", 2)); myList.list.Add(new Pair<string, int>("c", 2)); try { XmlSerializer serializer = new XmlSerializer(typeof(PairList<string, int>)); TextWriter tw = new StreamWriter("list.xml"); serializer.Serialize(tw, myList); tw.Close(); } catch (Exception xe) { MessageBox.Show(xe.Message); } 。欢迎任何有关如何避免此异常并序列化列表的想法。

1 个答案:

答案 0 :(得分:1)

只需在您的Pair<T, U>课程中添加无参数构造函数即可...

public Pair()
{
}
相关问题