我试图通过WebServices传递字典。 但它不可序列化。 所以我写了一个自己的类,使其可序列化:
using System;
using System.Net;
using System.Windows;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema;
namespace Platform
{
public class SaDictionary<TKey, TValue> : Dictionary<TKey, TValue>,
IXmlSerializable
{
#region Constructors
public SaDictionary() : base() { }
public SaDictionary(IDictionary<TKey, TValue> dictionary)
: base(dictionary) { }
public SaDictionary(IEqualityComparer<TKey> comparer)
: base(comparer) { }
public SaDictionary(int capacity)
: base(capacity) { }
public SaDictionary(IDictionary<TKey, TValue> dictionary,
IEqualityComparer<TKey> comparer)
: base(dictionary, comparer) { }
public SaDictionary(int capacity, IEqualityComparer<TKey> comparer)
: base(capacity, comparer) { }
//protected SaDictionary(SerializationInfo info,
// StreamingContext context)
// : base(info, context)
//{
//}
#endregion
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement(); //key
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement(); //value
this.Add(key, value);
reader.ReadEndElement(); //item
// reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement(); //key
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement(); //value
writer.WriteEndElement(); //item
}
}
}
}
但是我得到了一个ArrayOfXElement。 有没有办法将它强制转换为字典? 招呼
答案 0 :(得分:0)
如果您使用Visual Studio生成服务代理,则按“高级”按钮可以看到更改生成的数据类型的选项。例如,您可以将集合类型映射到通用列表或可观察集合,对于字典,您基本上可以告诉它映射到各种数据类型。
这应该会帮助你。