0
我試圖通過WebServices傳遞字典。 但它不可序列化。 所以我寫了自己的類,使得它可序列化:通過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回來。 有沒有辦法將它轉換回字典? greets
喜THX爲ansere但我仍然有一些問題:這樣做 現在: 服務提述─>新的服務參考 - > choose->高級 我得到一個菜單,在這裏我可以映射字典列表或數組。 但我想得到一個字典... 我得到了一個不可序列化的錯誤,所以我寫了上面的類,但現在我得到了arrayofxelement – Umit 2010-06-02 08:30:52