Dictionary是一个键值类型的集合。它有点像数组,但Dictionary的键可以是任何类型,内部使用Hash Table存储键和值。本篇自定义一个类型安全的泛型Dictionary
为了使自定义的泛型Dictionary
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
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文件。