创建一个可以序列化的Dictionary类

最近在调试项目的发现了一个错误,错误提示如下

反射类型“StockImageManage.Setting”时出错。

{"无法序列化 System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MP_ZDImageCheck_CS.TypePageCount, MP_ZDImageCheck_CS, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] 类型的成员 MP_ZDImageCheck_CS.BusinessParameter.TypePageCounts,因为它实现 IDictionary。"}

后来发现是StockImageManage.Setting里面包含一个Dictionary类型的属性,而Dictionary是无法序列化的,为了解决这个问题,于是就自己写了一个可以序列化的类SerializableDictionary。具体内容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MP_ZDImageCheck_CS
{

    //说明:开始时准备设计成SerializableDictionary<U, T>,后来发现在多数情况下的key只需要是字符串就足够了,所以就不理会U的类型,直接使用默认的string了。
    public class SerializableDictionary<T> :
        Dictionary<string, T>, //继承Dictionary
        System.Xml.Serialization.IXmlSerializable //要能够序列化,必须实现IXmlSerializable接口 
    {
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            throw new NotImplementedException();
        }

 

        //从xml文件中读取内容并转换为对象

        public void ReadXml(System.Xml.XmlReader reader)
        {
            if (reader.IsEmptyElement)
                return;

            Type type = typeof(T);
            PropertyInfo[] pis = type.GetProperties(); //获取类型T中的所有属性信息

            reader.Read();
            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                //当前节点的限定名。例如,对于元素 <bk:book>,Name 为 bk:book。
                string key = reader.Name;

 

                //调用类型的默认构造函数创建类型T的实例,并作为value值写入Dictionary对象中
                this[key] = (T)type.GetConstructor(new Type[] { }).Invoke(null);
                if (!reader.IsEmptyElement)
                {
                    reader.ReadStartElement();
                    if (reader.NodeType != System.Xml.XmlNodeType.EndElement)
                    {
                        foreach (PropertyInfo pi in pis)
                        {
                            pi.SetValue(this[key],
                                //根据属性的类型对读取出来的字符串进行转换
                                Convert.ChangeType(reader.ReadElementString(pi.Name), pi.PropertyType), null);
                        }
                    }
                }
                reader.Read();
            }
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            Type type = typeof(T);
            //获取对象的全部属性信息
            PropertyInfo[] pis = type.GetProperties();
            foreach (string key in this.Keys)
            {
                writer.WriteStartElement(key);

                //将对象的每一个属性名和属性值写入xml文件中
                foreach (PropertyInfo pi in pis)
                {
                    //<属性名>属性值</属性名>
                    //<pi.Name>pi.GetValue(this[key], null).ToString()</pi.Name>
                    writer.WriteElementString(pi.Name, pi.GetValue(this[key], null).ToString());
                }
                writer.WriteEndElement();
            }
        }
    }
}

调用方式如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace SerializeDemo
{

    public class Student
    {
        public string Code { get; set; }
        public int Age { get; set; }
        public string Name { get; set; }
    }


    public class School
    {
        public SerializableDictionary<Student> stuSettings { get; set; }
    }

   

    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.MyReadTest();
            Console.Read();
        }

        void MyReadTest()
        {
            School school = new School();
            XmlSerializer xs = new XmlSerializer(typeof(School));
            FileStream fs = new FileStream(@"d:\mytest.xml", FileMode.Open);
            school = (School)xs.Deserialize(fs);
        }
      
        void MyWriteTest()
        {
            School school = new School();
            school.stuSettings = new SerializableDictionary<Student>();
            school.stuSettings ["a01"] = new Student() { Age = 18, Name = "QQ", Code = "a01" };
            school.stuSettings ["a02"] = new Student() { Age = 81, Name = "FF", Code = "a02" };
            school.stuSettings ["b01"] = new Student() { Age = 58, Name = "DD", Code = "b01" };
            school.stuSettings ["b02"] = new Student() { Age = 7, Name = "MN", Code = "b02" };

            XmlSerializer xs = new XmlSerializer(typeof(School));
            FileStream fs = new FileStream(@"d:\mytest.xml", FileMode.Create);
            xs.Serialize(fs, school);
            fs.Close();
        }

    }
}

 

你可能感兴趣的:(xml,String,qq,null,Class,Dictionary)