2011-02-11 72 views
1

我們有一個類,我們試圖序列化其中包含一個字典。在另一個可序列化類中序列化IDictionary

我有可操作的代碼實現IXmlSerializable序列化字典,但有點丟失,因爲如何使用默認的XMLSerializer序列化對象,然後當它到達字典元素強制它使用定製的序列化程序。

目前,我已經爲整個對象打造了一個自定義序列化器,只要我能幫助它,因爲對象可能會在其整個生命週期內發生變化,我希望儘量減少可能導致未來混淆的自定義。

以下是我試圖序列化的類的減少樣本,實際的對象要大得多;

public class Report 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 

    //... 

    private Dictionary<string, string> _parameters = new Dictionary<string, string>(); 

} 

任何關於這個簡單的方法的建議將被讚賞。

回答

1

不幸的是,IXmlSerializable是一件全有或無關的事。爲了自己做什麼東西,你必須做這一切的所有,這是不理想的。

爲了讓它變得更加困難,處理器無法通過泛型處理太多問題,因此很難將某種類型的封裝用作解決方法。

+0

謝謝Marc。很高興知道我沒有錯過任何明顯的事情。 – JIng 2011-02-13 23:54:26

0

最初的問題出現,因爲我試圖找到一個可行的解決方案,用於字典的XML序列化(尤其是駐留在其他對象中的thos)。

在此期間,我找到了一個使用WCF DataContractSerializer的替代選項,它具有序列化字典的功能。最簡單的例子是這樣的:

using System.Collections.Generic; 
using System.IO; 
using System.Runtime.Serialization; 

namespace CodeSample 
{ 
class Report       
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    //...             
    private Dictionary<string, string> _parameters = new Dictionary<string, string>(); 

    public Dictionary<string, string> Parameters { 
     get { return _parameters; } 
     set { _parameters = value; }  
    } 
} 


class StartUp 
{ 
    static void Main() 
    { 
    System.IO.Stream fStream = new FileStream("C:\\Out.xml" , FileMode.Create); 
    Report x = new Report(); 
    Report y; 
    System.IO.Stream rStream; 

    // Presuming that Parameters is an exposed reference to the dictionary 
    x.Parameters.Add("Param1", "James2"); 
    x.Parameters.Add("Param2", System.DateTime.Now.ToString()); 
    x.Parameters.Add("Param3", 2.4.ToString()); 

    DataContractSerializer dcs = new DataContractSerializer(x.GetType()); 

    dcs.WriteObject(fStream, x); 

    fStream.Flush(); 
    fStream.Close(); 

    rStream = new FileStream("C:\\Out.xml", FileMode.Open); 

    y = (Report) dcs.ReadObject(rStream); 
    //y is now a copy of x 
    } 
} 

} 

不確定是否有任何未解決的缺點。