我正在使用此博客条目SerializableDictionary
中定义的内容来存储数据并将其传递给/从 WCF 服务传递。如果我使用值类型作为值,这很好用,因为它们可以很容易地装箱成为s。但是,如果我使用类似的东西<string, object>
object
new List<int>() { 5, 10 }
,我得到一个例外:
类型 System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] 不能在此上下文中使用。
根据这里的讨论,我应该使用value.GetType()
初始化XmlSerializer
;但是,虽然这让我可以序列化,但我不知道如何以一般方式反序列化回我的SerializableDictionary
.
我不确定是否有办法干净地更改它同时仍然允许<string, object>
作为我的类型参数 - 我可以将值序列化为二进制而不是 XML 并以这种方式传输它(相同的代码正在序列化和反序列化,所以我不是担心互操作性),但如果可能的话,我希望拥有 XML。
编辑
完整代码示例:
XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, object>));
SerializableDictionary<string, object> dic = new SerializableDictionary<string, object>();
dic["test"] = new List<int>() { 5, 10 };
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
serializer.Serialize(writer, dic);
string ser = sb.ToString();
解决方案
感谢Nico Schertler给了我正确的答案。我在这里发布我的最终代码,以防有人需要。这与第一个链接中的原始代码向后兼容,因此由该代码序列化的任何内容都可以由下面的反序列化。
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
#region " IXmlSerializable Members "
#region " WriteXml "
public void WriteXml(XmlWriter writer)
{
// Base types
string baseKeyType = typeof(TKey).AssemblyQualifiedName;
string baseValueType = typeof(TValue).AssemblyQualifiedName;
writer.WriteAttributeString("keyType", baseKeyType);
writer.WriteAttributeString("valueType", baseValueType);
foreach (TKey key in this.Keys)
{
// Start
writer.WriteStartElement("item");
// Key
Type keyType = key.GetType();
XmlSerializer keySerializer = GetTypeSerializer(keyType.AssemblyQualifiedName);
writer.WriteStartElement("key");
if (keyType != typeof(TKey)) { writer.WriteAttributeString("type", keyType.AssemblyQualifiedName); }
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
// Value
TValue value = this[key];
Type valueType = value.GetType();
XmlSerializer valueSerializer = GetTypeSerializer(valueType.AssemblyQualifiedName);
writer.WriteStartElement("value");
if (valueType != typeof(TValue)) { writer.WriteAttributeString("type", valueType.AssemblyQualifiedName); }
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
// End
writer.WriteEndElement();
}
}
#endregion
#region " ReadXml "
public void ReadXml(XmlReader reader)
{
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
{
return;
}
// Base types
string baseKeyType = typeof(TKey).AssemblyQualifiedName;
string baseValueType = typeof(TValue).AssemblyQualifiedName;
while (reader.NodeType != XmlNodeType.EndElement)
{
// Start
reader.ReadStartElement("item");
// Key
XmlSerializer keySerializer = GetTypeSerializer(reader["type"] ?? baseKeyType);
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
// Value
XmlSerializer valueSerializer = GetTypeSerializer(reader["type"] ?? baseValueType);
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
// Store
this.Add(key, value);
// End
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
#endregion
#region " GetSchema "
public XmlSchema GetSchema()
{
return null;
}
#endregion
#endregion
#region " GetTypeSerializer "
private static readonly Dictionary<string, XmlSerializer> _serializers = new Dictionary<string, XmlSerializer>();
private static readonly object _deadbolt = new object();
private XmlSerializer GetTypeSerializer(string type)
{
if (!_serializers.ContainsKey(type))
{
lock (_deadbolt)
{
if (!_serializers.ContainsKey(type))
{
_serializers.Add(type, new XmlSerializer(Type.GetType(type)));
}
}
}
return _serializers[type];
}
#endregion
}
我只写出与基本类型不同的类型,以降低 XML 的长度,并且我保留XmlSerializer
s 的静态列表,以防止到处实例化它们。我确实必须在开始时写出提供的类型,以便能够防止写出每个节点上的类型。