【问题标题】:xml serialization of generic class泛型类的xml序列化
【发布时间】:2013-06-09 15:56:58
【问题描述】:

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

首先,我创建了一个类 PairList 来保存对的列表,然后我创建了代表一对两个值的实际类,keyvalue

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

不幸的是,我遇到了一个例外:There was an error reflecting type: PairList[System.String,System.Int32]。欢迎任何关于如何避免此异常和序列化列表的想法。

【问题讨论】:

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


    【解决方案1】:

    只需向您的Pair&lt;T, U&gt; 类添加一个无参数构造函数,它就会工作...

    public Pair()
    {
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2014-12-20
    • 1970-01-01
    • 2018-04-27
    • 2011-07-29
    • 1970-01-01
    相关资源
    最近更新 更多