你的位置:首页 > ASP.net教程

[ASP.net教程]自定义一个可以被序列化的泛型DictionaryTKey,TValue集合


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


为了使自定义的泛型Dictionary<TKey, TValue>可以被序列化成

 

  public class MySerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, I
  {
    public System.
    {
      return null;
    }
    public void Read
    {
      //键的
      
      //值的
      
      //判断
      bool wasEmpty = reader.IsEmptyElement;
      reader.Read();
      if (wasEmpty)
      {
        return;
      }
      while (reader.NodeType != System.
      {
        //先读键
        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 Write
    {
      //键的
      
      //值的
      
      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();
      }
    }
  }

 

客户端使用

 

  class Program
  {
    static void Main(string[] args)
    {
      MySerializableDictionary<int, string> mySerializableDictionary = new MySerializableDictionary<int, string>();
      mySerializableDictionary.Add(1,"darren");
      mySerializableDictionary.Add(2, "jack");
      using (
      {
        writer.WriteStartDocument();
        writer.WriteStartElement("infos");
        foreach (var item in mySerializableDictionary)
        {
          mySerializableDictionary.Write
        }
        writer.WriteEndElement();
        writer.WriteEndDocument();
      }
      Console.WriteLine("写入
      Console.ReadKey();
    }
  }  

 

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