【问题标题】:c# DataContractSerializer with inheritancec# DataContractSerializer 与继承
【发布时间】:2015-12-03 13:48:36
【问题描述】:

当使用 DataContractSerializer 反序列化 XML 时,我遇到了基类序列的问题。没有任何派生类从 XML 反序列化:

<?xml version="1.0" encoding="utf-8" ?>

<Page xmlns="Renishaw.Page">
  <Fields>
    <Field Value="Welcome"/>
    <LanguageField Value="English"/>
  </Fields>

  <Buttons>
    <CancelButton/>
    <BackButton/>
    <NextButton/>
  </Buttons>

  <ChildPath>D:\SerializeTest\Console\bin\Debug\XML\Content\Next\Next\Page.xml</ChildPath>
</Page>

以下是我的DataContract

[DataContract(Namespace = "Renishaw.Page")]
internal class Page
{
    [DataMember(Order=1, IsRequired = true)]
    public List<Field> Fields { get; set; }

    [DataMember(Order = 2, IsRequired = true)]
    public List<Button> Buttons { get; set; }

    [IgnoreDataMember]
    public Page Child { get; set; }

    [DataMember(Order = 3, IsRequired = true)]
    private string ChildPath { get; set; }

    [OnDeserialized]
    private void OnDeserialized(StreamingContext context)
    {
        if (ChildPath.Equals(""))
            return;

        Child = Serializer.Deserialize<Page>(ChildPath);
    }

    [OnSerialized]
    private void OnSerialized(StreamingContext context)
    {

    }
}

[DataContract]
[KnownType(typeof(LanguageField))]
internal class Field
{
    [DataMember(Order=1)]
    public string Value { get; set; }
}

[DataContract]
internal class LanguageField : Field
{

}

[DataContract]
[KnownType(typeof(BackButton))]
[KnownType(typeof(CancelButton))]
[KnownType(typeof(NextButton))]
internal class Button
{

}

[DataContract]
internal class BackButton : Button
{

}

[DataContract]
internal class CancelButton : Button
{

}

[DataContract]
internal class NextButton : Button
{

}

我到底哪里错了?您是否需要为继承的项目声明 contract 的特定方式?

【问题讨论】:

    标签: c# .net xml datacontractserializer datacontract


    【解决方案1】:

    您应该将DataContract 名称添加到Button,如下所示

    [DataContract(Name="ThisIsButton")]
    [KnownType(typeof(BackButton))]
    [KnownType(typeof(CancelButton))]
    [KnownType(typeof(NextButton))]
    internal class Button
    {
    
    }
    

    然后在你的xml中添加itype

      <Buttons>
        <CancelButton itype="ThisIsButton"/>
        <BackButton itype="ThisIsButton"/>
        <NextButton itype="ThisIsButton"/>
      </Buttons>
    

    【讨论】:

    • 我认为你是对的。命名空间需要应用于每个数据契约,然后 i:type 可以添加到每个派生类型,即:
    猜你喜欢
    • 2010-11-13
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 2010-10-18
    • 2012-01-11
    • 1970-01-01
    相关资源
    最近更新 更多