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中當前節點是否為nullbool 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文件。