2011-03-24 57 views
1


我有以下類:XML序列化 - 出了什麼問題? C#

   public class ObjectCollection : List<ObjectRow> 
       { 

        public Dictionary<int, ObjectRow> ObjectsAutomat { get; private set; } 
        public Dictionary<int, ObjectRow> ObjectsDelayed { get; private set; } 
        public Dictionary<int, ObjectRow> ObjectsHandle { get; private set; } 
        public Dictionary<int, ObjectRow> ObjectsNew { get; private set; } 

        public Dictionary<string, string> Fields 
        { get; protected set; } 

        public string AddressParserFieldName { get; set; } 
     // Some methods here 

       } 

     public class ObjectRow 
     { 
      public int ID { get; set; } 
      public int Position { get; set; } 
      public AddressParserResult AddressParserResult { get; set; } 
      public ObjectStatus Status { get; set; } 
      public virtual List<Item> Items { get; set; } 

      public Item this[string fieldName] 
      { 
       get { /* Some code */} 
       set { /* Some code */} 
      } 

      public Item this[int index] 
      { 
       get { return Items[index]; } 
       set { Items[index] = value; } 
      } 
     } 

而且我希望能夠序列化/反序列化ObjectCollection。當我嘗試像這樣執行xml序列化時:

var xmlSerializer = new XmlSerializer(typeof(ObjectsCollection)); 
using(var sw = new StreamWriter(fileName, false, Encoding.GetEncoding(CODE_PAGE))) 
{ 
    xmlSerializer.Serialize(sw, objectsCollection); 
} 
using (var sr = new StreamReader(fileName, Encoding.GetEncoding(CODE_PAGE))) 
{ 
    var deserializedObjectsCollection = xmlSerializer.Deserialize(sr) as ObjectsCollection; 
} 

我沒有得到我以前的對象。哪裏不對?
在此先感謝!

+2

你會得到什麼? – RQDQ 2011-03-24 12:43:59

+0

您的類甚至未標記爲XmlRoot,並且您的屬性未標記爲XmlElement或XmlAttribute。你能解釋一下你所得到的結果嗎?爲什麼它「不是你以前的對象?」 – 2011-03-24 12:45:00

+0

除了@ RQDQ的評論 - 你檢查了生成的XML,看看是否有明顯的錯誤? – 2011-03-24 12:45:26

回答

3

你不能序列化一個實現了IDictionary的類。看看這link

XmlSerializer無法處理實現IDictionary接口的類。部分原因是由於進度約束,部分原因是哈希表在XSD類型系統中沒有對應項。唯一的解決方案是實現一個不實現IDictionary接口的自定義哈希表。

+0

關於Dictionary(Foo,Bar)作爲IEnumerable(KeyValuePair(的Foo,Bar))有什麼問題,或者允許一個類的反序列化實現IEnumerable(的KeyValuePair(Foo,Bar的))並且有一個add(foo,bar)方法,或者說服Dictionary加載器爲Add(KeyValuePair(Of Foo,Bar))添加一個重載。 – supercat 2011-03-24 20:39:36