【发布时间】:2021-11-05 13:47:38
【问题描述】:
使用XmlSerializer反序列化时
案例 1:
Presentation 包含 Slide 类型的子元素
<Presentation>
<Slide>
...
</Slide>
</Presentation>
nameof 获取正确的结果,即应该传递elementName。用typeof 替换它会得到不正确的结果。
public class Presentation
{
...
[XmlElement(nameof(Slide))]
public List<Slide> Slides { get; set; }
...
}
案例 2:
Slide 包含从基类Shape 派生的TextBox 或Table 类型的子元素
<Slide>
<TextBox>
...
</TextBox>
<Table>
...
</Table>
</Slide>
typeof 获取正确的结果,即应该传递type。用nameof 替换它会得到不正确的结果。
public class Slide
{
...
[XmlElement(typeof(TextBox))]
[XmlElement(typeof(Table))]
public List<Shape> Shapes { get; set; }
...
}
任何人都可以解释上述内容吗?什么时候提供元素名称,什么时候提供类型?
【问题讨论】:
-
并非如此。如果相应的未完成,则 XML 不会正确反序列化。
标签: c# .net xml attributes deserialization