2011-02-11 65 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 
    } 
} 

} 

不确定是否有任何未解决的缺点。