在C#中反序列化XML时,如何获得对父对象的引用?
-
03-07-2019 - |
题
我似乎无法使其工作,这是我的(剥离)代码: -
[XmlRoot("report")]
public class Report
{
[XmlArray("sections"), XmlArrayItem("section")]
public List<Section> Sections;
}
public class Section
{
public Report Report;
}
我错过了什么吗?
解决方案
您的对象包含循环引用, XmlSerializer 类。您可以改为查看 DataContractSerializer 支持此类方案。
其他提示
您应该确保知道这些类是如何序列化和反序列化的。编写您想要的XML作为结果,并弄清楚您希望对象如何成为XML,反之亦然。这不是一个明智的选择。
这是我的解决方案。它可能没有你想象的那么优雅:
public class Report
{
//...
void PostLoad()
{
foreach(Section s in Sections)
{
s.Report = this;
}
}
public static Report Load(string filename)
{
// Load using an XmlSerializer
Report report = ...;
report.PostLoad();
return report;
}
}
不隶属于 StackOverflow