【问题标题】:Inherit XMLType of base class继承基类的 XMLType
【发布时间】:2014-09-30 19:37:37
【问题描述】:

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

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

以及下面的继承类,没有 XMLType 属性装饰类

[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 被替换而不显式强制它)以及如何实现所需的行为?

【问题讨论】:

    标签: c# xml inheritance serialization


    【解决方案1】:

    我实现了所需的行为,只需使用 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

    【讨论】:

    • 我无法使用示例中的 XmlInclude 使其工作。你能验证基类和继承类并检查你发布的代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多