xml使用它的泛型类型序列化泛型类

时间:2013-06-09 16:21:37

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

我需要将包含Pair<T,U>类型对象的列表序列化为xml。除了这些值,我还需要序列化它的泛型类型(TU的类型)。

首先,我创建了一个类PairList来保存对的列表,然后我创建了实际的类,它表示一对两个值,键和值。

 [XmlRoot("pairList")]
        public class PairList<T,U>{
            [XmlElement("element")]
            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;
            [XmlAttribute("T-Type")]
            public Type ttype;
            [XmlAttribute("U-Type")]
            public Type utype;

            public Pair()
            {
            }
            public Pair(T t, U u)
            {
                key = t;
                value = u;
                ttype = typeof(T);
                utype = typeof(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]。欢迎任何有关如何避免此异常并序列化该类的想法。

如果我选择不序列化ttypeutype字段(通过使它们受保护或私有),则序列化可以正常工作。我无法弄清楚为什么它不想序列化Type字段。

1 个答案:

答案 0 :(得分:0)

将班级更改为

public class Pair<T, U>
{
    [XmlAttribute("key")]
    public T key;
    [XmlAttribute("value")]
    public U value;
    [XmlAttribute("T-Type")]
    public string ttype;
    [XmlAttribute("U-Type")]
    public string utype;

    public Pair()
    {
    }
    public Pair(T t, U u)
    {
        key = t;
        value = u;
        ttype = typeof(T).ToString();
        utype = typeof(U).ToString();
    }
}

它应该有效。您无法使用Type序列化/反序列化Xmlserializer。(例如,假设T是外部程序集中定义的复杂对象,并且此程序集不存在于您希望的计算机上反序列)

相关问题