1

我在将对象反序列化为 XML 时遇到了一些麻烦。我正在尝试反序列化没有空构造函数的东西,因此我需要使用 BinaryFormatter?我有:

  • 一个 DLL,它包含一个我想反序列化为 XML 的类。
  • 从反映类型我可以看出它没有无参数构造函数。
  • 此类包含一些属性,其中一些也没有空构造函数。

我的问题是,是否可以将此类反序列化为 XML?我确实找到了一种使用方法:

  • 二进制格式化程序
  • 将内容加载到流中
  • 使用 FileStream 写入其内容,但以垃圾结束

提前致谢。我发现了一个叫做 FormatterServices 的东西……但不知道你是否可以将它与 XmlSerializer 结合使用?

4

1 回答 1

0
  1. 将二进制数据反序列化回对象。

  2. 将您的对象复制到代理对象中。

  3. Xml 序列化您的代理对象。

假设您的原始非 xml 可序列化对象的类型是“Foo”

[XmlRoot]
public class FooSurrogate {

     public FooSurrogate() { }; // note the empty constructor for xml deserialization

     public FooSurrogate(Foo foo) {  // this constructor is used in step 2
          // in here you copy foo's state into this object's state
          this.Prop1 = foo.Prop1; // this prop can be copied directly 
          this.Bar = new BarSurrogate(foo.Bar); // this prop needs a surrogate as well  
     } 

     [XmlAttribute]  // note your surrogate can be used to xml-format too!
     public string Prop1 { get; set; }

     [XmlElement]
     public BarSurrogate Bar { get; set; }

}

public class BarSurrogate { 
...
}
于 2013-02-28T14:11:11.140 回答