Dictionary是一个键值类型的集合。它有点像数组,但Dictionary的键可以是任何类型,内部使用Hash Table存储键和值。本篇自定义一个类型安全的泛型Dictionary<TKey, TValue>,并且可以被序列化。

为了使自定义的泛型Dictionary<TKey, TValue>可以被序列化成xml,需要实现泛型IXmlSerializable接口。

    public class MySerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
    {
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            //键的xml序列化器
            XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));

            //值的xml序列化器
            XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

            //判断xml中当前节点是否为null
            bool wasEmpty = reader.IsEmptyElement;

            reader.Read();

            if (wasEmpty)
            {
                return;
            }

            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
               //先读键
                reader.ReadStartElement("item");
                reader.ReadStartElement("key");

                //反序列化成键的类型
                TKey key = (TKey) keySerializer.Deserialize(reader);
                reader.ReadEndElement();

                //再读值
                reader.ReadStartElement("value");
                TValue value = (TValue)valueSerializer.Deserialize(reader);
                reader.ReadEndElement();

                this.Add(key, value);
                reader.ReadEndElement();

                //读下一个节点
                reader.MoveToContent();
            }

            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            //键的xml序列化器
            XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));

            //值的xml序列化器
            XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

            foreach (TKey key in this.Keys)
            {
                writer.WriteStartElement("item");
                writer.WriteStartElement("key");
                keySerializer.Serialize(writer, key);
                writer.WriteEndElement();

                writer.WriteStartElement("value");
                TValue value = this[key];
                valueSerializer.Serialize(writer, value);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }
    }


客户端使用XmlWriter把Dictionary<TKey, TValue>这个泛型集合写进xml中。

    class Program
    {
        static void Main(string[] args)
        {
            MySerializableDictionary<int, string> mySerializableDictionary = new MySerializableDictionary<int, string>();
            mySerializableDictionary.Add(1,"darren");
            mySerializableDictionary.Add(2, "jack");

            using (XmlWriter writer = XmlWriter.Create("infos.xml"))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("infos");

                foreach (var item in mySerializableDictionary)
                {
                    mySerializableDictionary.WriteXml(writer);
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
            Console.WriteLine("写入xml成功");
            Console.ReadKey();
        }
    }

在Debug文件夹中可找到生成的infos.xml文件。

自定义一个可以被序列化的泛型Dictionary<TKey,TValue>集合的更多相关文章

  1. 使用结构struct作为Dictionary<TKey,TValue>的键

    我们经常用简单数据类型,比如int作为泛型Dictionary<TKey,TValue>的key,但有时候我们希望自定义数据类型作为Dictionary<TKey,TValue> ...

  2. 泛型与非泛型集合类的区别及使用例程,包括ArrayList,Hashtable,List<T>,Dictionary<Tkey,Tvalue>,SortedList<Tkey,Tvalue>,Queue<T>,Stack<T>等

    泛型与非泛型集合类在C#程序中是非常重要的一个基础概念,这里列一个表来进行对比: 非泛型集合类 泛型集合类 描述 ArrayList List<T> 表示具有动态大小的对象数组 Hasht ...

  3. C#中数组、集合(ArrayList)、泛型集合List<T>、字典(dictionary<TKey,TValue>)全面对比

    C#中数组.集合(ArrayList).泛型集合List<T>.字典(dictionary<TKey,TValue>)全面对比 为什么把这4个东西放在一起来说,因为c#中的这4 ...

  4. .NET中Dictionary<TKey, TValue>浅析

    .NET中Dictionary<TKey, Tvalue>是非常常用的key-value的数据结构,也就是其实就是传说中的哈希表..NET中还有一个叫做Hashtable的类型,两个类型都 ...

  5. C#编程(五十三)----------字典Dictionary<TKey,TValue>

    字典 关键字:Dicitionary 说明: 必须包含命名空间System.Collection.Generic Dictionary里面的每一个元素都是一个键值对(由两个元组组成:键和值). 键必须 ...

  6. Dictionary<TKey, TValue> 类

    C# Dictionary<TKey, TValue> 类 Dictionary<TKey, TValue> 泛型类提供了从一组键到一组值的映射.字典中的每个添加项都由一个值及 ...

  7. Dictionary<Tkey.TValue>与SortedList

    一.概述 表示Key/Value集合,可以添加删除元素,允许按Key来访问元素.是Hashtable的泛型等效类. 它需要一个相等实现来确定键是否相等,可以使用实现了IEqualityComparer ...

  8. .net源码分析 – Dictionary<TKey, TValue>

    接上篇:.net源码分析 – List<T> Dictionary<TKey, TValue>源码地址:https://github.com/dotnet/corefx/blo ...

  9. C# 字典 Dictionary<Tkey,Tvalue>

    最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来.我们都知道计算机技术发展日新月异,速度惊人的快,你我稍不留神,就会被慢慢淘汰!因此:每日不间断的学习是避免被 ...

随机推荐

  1. Number of Airplanes in the Sky

    Given an interval list which are flying and landing time of the flight. How many airplanes are on th ...

  2. Number of Islands I & II

    Given a boolean 2D matrix, find the number of islands. Notice 0 is represented as the sea, 1 is repr ...

  3. Hadoop 上使用C 语言编程【转】

    转自:https://www.linuxidc.com/Linux/2012-04/58991.htm 今天尝试用C语言在Hadoop上编写统计单词的程序,具体过程如下: 一.编写map和reduce ...

  4. 内存对齐与ANSI C中struct型数据的内存布局 【转】

    转自:http://blog.chinaunix.net/uid-25909619-id-3032209.html 当在C中定义了一个结构类型时,它的大小是否等于各字段(field)大小之和?编译器将 ...

  5. 2012 Dhaka

    2012 Dhaka B - Wedding of Sultan 题目描述:给出一棵树的\(dfs\)序(只要经过就会记录),求每个点的度 solution 按\(dfs\)序的规则还原这棵树就好了. ...

  6. 10 Go 1.10 Release Notes

    Go 1.10 Release Notes Introduction to Go 1.10 Changes to the language Ports Tools Default GOROOT &am ...

  7. Pandas DataFrame数据的增、删、改、查

    Pandas DataFrame数据的增.删.改.查 https://blog.csdn.net/zhangchuang601/article/details/79583551 #删除列 df_2 = ...

  8. postman发送json请求,使用案例

    介绍:  postman是一个很好的http模拟器,,可以发送get.post.put等各种请求,是测试服务接口相当好的工具. postman发送json请求,使用案例 发送json的具体步骤: 1. ...

  9. python学习之算法、自定义模块、系统标准模块(上)

    算法.自定义模块.系统标准模块(time .datetime .random .OS .sys .hashlib .json和pickle) 一:算法回顾: 冒泡算法,也叫冒泡排序,其特点如下: 1. ...

  10. SendMessage原理初探

    今天跟踪一下SendMessage的实现. 用向导先创建一个Windows application. 向导生成了一个简单的窗口,如下. 在File菜单添加SendMessage,顺便添加一个PostM ...