gpt4 book ai didi

c# DataContractSerializer 继承

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:29 27 4
gpt4 key购买 nike

当使用 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)

最佳答案

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

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

}

然后在你的xml中添加type

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

关于c# DataContractSerializer 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34067720/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com