我如何反序列化XML转换成使用一个构造函数一个XDocument对象?转换成、函数、对象、序列化

2023-09-04 00:40:23 作者:葬

我有一个类:

public class MyClass
{
   public MyClass(){}
}

我希望能够在构造函数中这样使用XMLSeralizer反序列化一个XDocument直接:

I would like to be able to use an XMLSeralizer to Deserialize an XDocument directly in the constructor thus:

public class MyClass
{
   private XmlSerializer _s = new XmlSerializer(typeof(MyClass));

   public MyClass(){}
   public MyClass(XDocument xd)
   {
      this = (MyClass)_s.Deserialize(xd.CreateReader());
   }
}

除了我不能在构造函数中分配到本。

Except I am not allowed to assign to "this" within the constructor.

这可能吗?

推荐答案

没有,这是不可能的。串行器创建对象时,他们反序列化。你已经创建的对象。相反,提供了一个静态方法从一个XDocument建设。

No, it's not possible. Serializers create objects when they deserialize. You've already created an object. Instead, provide a static method to construct from an XDocument.

public static MyClass FromXml (XDocument xd)
{
   XmlSerializer s = new XmlSerializer(typeof(MyClass));
   return (MyClass)s.Deserialize(xd.CreateReader());
}