【问题标题】:xml serialize a generic class with it's generic typesxml 用它的泛型类型序列化一个泛型类
【发布时间】:2013-06-09 16:21:37
【问题描述】:

我需要将包含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 字段。

【问题讨论】:

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


    【解决方案1】:

    把你的班级改成

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

    它应该可以工作。您不能用Xmlserializer 序列化/反序列化Type。(例如,假设T 是在外部程序集中定义的复杂对象,并且该程序集在您要反序列化的计算机上不存在)

    【讨论】:

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