SerializableDictionary-一个支持序列化与反序列化的Dictionary
使用Dictionary存储的信息在试图序列化为XML保存到文件时,会遇到无法序列化的问题,由于官方Dictionary不支持xml序列化,所以有朋友已经通过实现IXmlSerializable接口,封装了SerializableDictionary,并在园子里分享了原代码。原文链接http://www.cnblogs.com/cpcpc/p/3678785.html 感谢朋友的分享。
使用过程中,遇到了两个问题:
1.Key为字符串是,期望可以大小写无关,这点在Dictionary中是支持的,通过在构造函数中传入一个IEqualityComparer
2.当Dictionary在XML中不是根目录时,可能会因为Dictionary的Count为0的原因在序列化时缺少必要的节点信息,从而导致反序列化时出错。
基于以上两点原因,在使用过程中对SerializableDictionary进行了补充,实际测试效果OK,当然还有其它地方还需要完善,但时间有限,有做了这些调整。
本着致谢、共享的精神,把代码贴出来,欢迎大家拍砖,也希望大家能进一步完善和修正。
using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Xml; using System.Xml.Schema; [Serializable] public class SerializableDictionary: Dictionary , IXmlSerializable { public SerializableDictionary() { } public SerializableDictionary(IEqualityComparer comparer) : base(comparer) { } public void WriteXml(XmlWriter write) // Serializer { XmlSerializer KeySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer ValueSerializer = new XmlSerializer(typeof(TValue)); foreach (KeyValuePair kv in this) { write.WriteStartElement("SerializableDictionary"); write.WriteStartElement("key"); KeySerializer.Serialize(write, kv.Key); write.WriteEndElement(); write.WriteStartElement("value"); ValueSerializer.Serialize(write, kv.Value); write.WriteEndElement(); write.WriteEndElement(); } } public void ReadXml(XmlReader reader) // Deserializer { reader.Read(); XmlSerializer KeySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer ValueSerializer = new XmlSerializer(typeof(TValue)); if (reader.Name == "SerializableDictionary") { while (reader.NodeType != XmlNodeType.EndElement) { reader.ReadStartElement("SerializableDictionary"); reader.ReadStartElement("key"); TKey tk = (TKey)KeySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue vl = (TValue)ValueSerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadEndElement(); this.Add(tk, vl); reader.MoveToContent(); } reader.ReadEndElement(); } } public XmlSchema GetSchema() { return null; } XmlSchema IXmlSerializable.GetSchema() { throw new NotImplementedException(); } }
实际调用代码:
public SerializableDictionary<string, string> FieldMappings { get; set; } = new SerializableDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
用来存储一个数据库表字段名映射信息,Key忽略大小写。