1,SerializableAttribute不存在
在Silverlight中,已經不包含SerializableAttribute,不過沒有了這個標記 也不會影響序列化。去除這個特性標記的原因,是因為已經了一系列XML為開頭的 用於序列化的特性標記。
對於這個變動,沒有什麼痛點,主要是比較麻煩,需要逐一刪除。當然如果不 想刪除,最簡單的方式就是,自己建立一個SerializableAttribute 。
2,Dictionary的xml序列化,用XElement代替XmlDocument, Convert.ChangeType的參數變化
說起來,就是不在Silverlight中,也沒有辦法用XmlSerializer對 Dictionary<>進行序列化。而我直接實現了一個能夠Xml序列化的 Dictionary,代碼如下:
public class XmlSerDictionary<TKey, Tvalue> : Dictionary<TKey, Tvalue>, IXmlSerializable
{
#region IXmlSerializable Members
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(reader.ReadOuterXml());
foreach (XmlElement item in doc.ChildNodes [0].ChildNodes)
{
TKey key = (TKey)Convert.ChangeType (item.GetAttribute("key"), typeof(TKey));
Tvalue value = (Tvalue)Convert.ChangeType (item.InnerText, typeof(Tvalue));
this.Add(key, value);
}
}
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
{
foreach (var item in this)
{
writer.WriteStartElement("item");
writer.WriteAttributeString("key", item.Key.ToString());
writer.WriteValue(item.Value);
writer.WriteEndElement();
}
}
#endregion
}