2012-01-26 43 views
1

我收到以下錯誤,當我試圖序列List<SLItem>錯誤XML序列

有反射式「的錯誤System.Collections.Generic.List`1

[Serializable] 
public class SLItem 
{ 
    public int ID { get; set; } 
    public string ActorName { get; set; } 
    public Dictionary<string, List<string>> VerLookup { get; set; } 
    public bool IsEnabled { get; set; } 
} 

我在這裏錯過了什麼。

回答

2

Instead of the Dictionary use一個列表:

[Serializable] 
public struct KeyValuePair<K,V> 
{ 
    public K Key {get;set;} 
    public V Value {get;set;} 
} 

所以你的字典變爲:

List<KeyValuePair<string, List<string>>> 

的XmlSerializer無法序列已只讀屬性的類。字典包含KeyValuePair <>,它們使用只讀鍵和值屬性實現。

0

您可以製作一個實現IXmlSerializable的子類。 前段時間我創建了它並將其序列化爲XML作品。 這是代碼!

using System.Xml.Serialization; 
using System.Xml.Schema; 
using System.Xml; 


[XmlRoot("dictionary")] 
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable 
{ 
    #region IXmlSerializable Members 

    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(); 
      reader.ReadStartElement("value"); 
      TValue value = (TValue)valueSerializer.Deserialize(reader); 
      reader.ReadEndElement(); 
      this.Add(key, value); 
      reader.ReadEndElement(); 
      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(); 
      writer.WriteStartElement("value"); 
      TValue value = this[key]; 
      valueSerializer.Serialize(writer, value); 
      writer.WriteEndElement(); 
      writer.WriteEndElement(); 
     } 
    } 

    #endregion 
}