c# - 如何使用采用 XDocument 的构造函数将 XML 反序列化为对象?

标签 c# .net xml xml-serialization linq-to-xml

我有一个类:

public class MyClass
{
   public MyClass(){}
}

我希望能够使用 XMLSeralizer 直接在构造函数中反序列化 XDocument,因此:

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

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

除非我不允许在构造函数中分配给“this”。

这可能吗?

最佳答案

不,这不可能。序列化程序在反序列化时创建对象。您已经创建了一个对象。相反,提供一个从 XDocument 构造的静态方法。

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

关于c# - 如何使用采用 XDocument 的构造函数将 XML 反序列化为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7901558/

相关文章:

c# - 队列管理系统

xml - Perl 编辑 XML 文件 : search and replace

ios - 为什么我从 xml Web 服务器对 iOS 的响应中得到终止错误?

c# - IEnumerable 模型中的多个 DropDownList

c# - 在 WPF 中打开 WebView2 会在调用 EnsureCoreWebView2Async 时导致 System.UnauthorizedAccessException

c# - 对您来说它看起来像 C# 错误吗?

java - 如果存在 xsi :type and a different namespace prefix,xmlunit.Diff 返回 similar=false

c# - switch 样式 C# 构造双范围案例

c# - ConfigureAwait(false) 导致错误而不是死锁的情况

c# - 为什么Selenium GECKO driver for Firefox 48 无法启动服务器?