继承基类的XMLType

2024-01-20

我有以下用 XmlType 属性装饰的基类

[Serializable]
[XmlType("Base")]
public class Base
{
    [XmlElement(ElementName = "IdBase")]
    public int IdBase { get; set; }
    ...
}

以及以下继承类,withoutXMLType 属性装饰类

[Serializable]
public class InheritedClass1 : Base
{
    [XmlElement(ElementName = "InheritedProp")]
    public int InheritedProp{ get; set; }
    ...
}

当我序列化时,继承的类似乎会覆盖生成以下 XML 的 XmlType(这是我没有预料到的,因为我没有使用 XmlType 显式修饰)

<InheirtedClass1>
    <IdBase>1</IdBase>
    <InheritedProp>1</InheritedProp>
    ...
</InheirtedClass1>

这就是我期望的 XML

<Base>
    <IdBase>1</IdBase>
    <InheritedProp>1</InheritedProp>
    ...
</Base>

如果我尝试使用 [XmlType("Base")] 属性装饰继承的类,但是当我创建 XmlSerializer(typeof(InheirtedClass1)) 的实例时会引发异常,因为它重复了 XmlType,这是有道理的...

有人可以解释为什么会发生这种情况(XmlType 被替换而不显式强制它)以及如何实现所需的行为?


我实现了所需的行为,只需使用以下结尾的 XmlInclude 属性来装饰基类,并使用基类类型的 XmlSerializer

[Serializable]
[XmlType("Base")]
[XmlInclude(typeof(InheritedClass1))] //Missing This line! 
public class Base
{
     [XmlElement(ElementName = "IdBase")]
     public int IdBase { get; set; }
     ...
}

这个答案基于 Marc Gravell 对以下问题的回答(在我的第一次搜索中,我找不到这个问题,它与我的问题基本相同)

https://stackoverflow.com/a/12237360/2237027 https://stackoverflow.com/a/12237360/2237027

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

继承基类的XMLType 的相关文章

随机推荐