C# 序列化 .NET 字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1299071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Serializing .NET dictionary
提问by devnull
Possible Duplicate:
Serialize Class containing Dictionary member
可能的重复:
序列化包含字典成员的类
Can I serialize a Dictionary?
我可以序列化字典吗?
回答by Marc Gravell
Which serialization API?
哪个序列化API?
For example, DataContractSerializer
can handle dictionaries, especially with the (optional) [CollectionDataContract]
markup. protobuf-net will handle them (below). Others may not...
例如,DataContractSerializer
可以处理字典,尤其是使用(可选)[CollectionDataContract]
标记。protobuf-net 将处理它们(如下)。别人可能不...
var data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);
var clone = Serializer.DeepClone(data);
Console.WriteLine(clone["abc"]);
Console.WriteLine(clone["def"]);
As will BinaryFormatter
:
将BinaryFormatter
:
using (MemoryStream ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, data);
ms.Position = 0;
clone = (Dictionary<string, int>) bf.Deserialize(ms);
}
回答by Scott Lerch
Not without using another serialization library or implementing serialization yourself. Neither Hashtable or Dictionary are serializable out of the box in .NET. There is an implementation of a SerializableDictionary herethat does both XML and binary serialization.
不是没有使用另一个序列化库或自己实现序列化。Hashtable 或 Dictionary 都不能在 .NET 中开箱即用地序列化。有一个SerializableDictionary的实现在这里,做XML和二进制序列化。
Here is the code from the link (Copyright (c) Dacris Software Inc. MIT license):
这是链接中的代码(版权所有 (c) Dacris Software Inc. MIT 许可证):
using System;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Text;
[Serializable()]
public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, IXmlSerializable, ISerializable
{
#region Constants
private const string DictionaryNodeName = "Dictionary";
private const string ItemNodeName = "Item";
private const string KeyNodeName = "Key";
private const string ValueNodeName = "Value";
#endregion
#region Constructors
public SerializableDictionary()
{
}
public SerializableDictionary(IDictionary<TKey, TVal> dictionary)
: base(dictionary)
{
}
public SerializableDictionary(IEqualityComparer<TKey> comparer)
: base(comparer)
{
}
public SerializableDictionary(int capacity)
: base(capacity)
{
}
public SerializableDictionary(IDictionary<TKey, TVal> dictionary, IEqualityComparer<TKey> comparer)
: base(dictionary, comparer)
{
}
public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer)
: base(capacity, comparer)
{
}
#endregion
#region ISerializable Members
protected SerializableDictionary(SerializationInfo info, StreamingContext context)
{
int itemCount = info.GetInt32("ItemCount");
for (int i = 0; i < itemCount; i++)
{
KeyValuePair<TKey, TVal> kvp = (KeyValuePair<TKey, TVal>)info.GetValue(String.Format("Item{0}", i), typeof(KeyValuePair<TKey, TVal>));
this.Add(kvp.Key, kvp.Value);
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ItemCount", this.Count);
int itemIdx = 0;
foreach (KeyValuePair<TKey, TVal> kvp in this)
{
info.AddValue(String.Format("Item{0}", itemIdx), kvp, typeof(KeyValuePair<TKey, TVal>));
itemIdx++;
}
}
#endregion
#region IXmlSerializable Members
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
{
//writer.WriteStartElement(DictionaryNodeName);
foreach (KeyValuePair<TKey, TVal> kvp in this)
{
writer.WriteStartElement(ItemNodeName);
writer.WriteStartElement(KeyNodeName);
KeySerializer.Serialize(writer, kvp.Key);
writer.WriteEndElement();
writer.WriteStartElement(ValueNodeName);
ValueSerializer.Serialize(writer, kvp.Value);
writer.WriteEndElement();
writer.WriteEndElement();
}
//writer.WriteEndElement();
}
void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
{
if (reader.IsEmptyElement)
{
return;
}
// Move past container
if (!reader.Read())
{
throw new XmlException("Error in Deserialization of Dictionary");
}
//reader.ReadStartElement(DictionaryNodeName);
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement(ItemNodeName);
reader.ReadStartElement(KeyNodeName);
TKey key = (TKey)KeySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement(ValueNodeName);
TVal value = (TVal)ValueSerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadEndElement();
this.Add(key, value);
reader.MoveToContent();
}
//reader.ReadEndElement();
reader.ReadEndElement(); // Read End Element to close Read of containing node
}
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
#endregion
#region Private Properties
protected XmlSerializer ValueSerializer
{
get
{
if (valueSerializer == null)
{
valueSerializer = new XmlSerializer(typeof(TVal));
}
return valueSerializer;
}
}
private XmlSerializer KeySerializer
{
get
{
if (keySerializer == null)
{
keySerializer = new XmlSerializer(typeof(TKey));
}
return keySerializer;
}
}
#endregion
#region Private Members
private XmlSerializer keySerializer = null;
private XmlSerializer valueSerializer = null;
#endregion
}