我正在尝试将一些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 =”类型itk.cda.cdaclasses.p_recordTarget不是预期的。使用XmlInclude或SoapInclude属性指定静态未知的类型。“
所以我想我需要一个XmlInclude,但我不确定如何。
答案 0 :(得分:2)
简而言之,您需要使用基类上的属性让序列化程序了解派生类:
[XmlInclude(typeof(p_recordTarget))]
public class ParticipationClass {
// ...
}
答案 1 :(得分:1)
答案 2 :(得分:1)
像这样:
[XmlInclude(typeof(p_recordTarget))]
public class ParticipationClass
{
[XmlAttribute]
public string typeCode;
[XmlAttribute]
public string contextControlCode;
public ParticipationClass()
{
}
}