我正在尝试将一些 C# 类序列化为 XML。在我尝试引入一些继承的类之前,一切都很顺利。
类是[根据大小编辑的]
public class ParticipationClass
{
[XmlAttribute]
public string typeCode;
[XmlAttribute]
public string contextControlCode;
public ParticipationClass()
{
}
}
public class p_recordTarget : ParticipationClass
{
public p_recordTarget()
{
typeCode = "RCT";
contextControlCode = "OP";
}
}
使用类时,使用以下代码:
public class Test
{
// other class attributes excluded..
[XmlElement]
public ParticipationClass recordTarget;
private void Test()
{
recordTarget = new p_recordTarget();
}
}
序列化因 InvalidOperationException 而失败,查看异常详细信息我可以看到“Message="The type itk.cda.cdaclasses.p_recordTarget was not expected.使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。”
所以我想我需要一个 XmlInclude,但我不确定该怎么做。
请您参考如下方法:
简而言之,您需要使用基类上的属性让序列化程序知道派生类:
[XmlInclude(typeof(p_recordTarget))]
public class ParticipationClass {
// ...
}
