【发布时间】:2009-07-20 14:07:37
【问题描述】:
我似乎对以下代码的 sn-p 存在问题,当我开始指定项目是什么时(例如 CashInHand),实际类型 CashInHandPayment 不可用,因为它没有被传递当我生成代理类时(很可能是因为它没有在 XmlElementAttributes 中读取)。
有没有办法强制在代理类中序列化AccountPayment、CashInHandPayment和CCPayment等类?
[DataContract]
public class Payment
{
[XmlElementAttribute("Account", typeof(AccountPayment))]
[XmlElementAttribute("CashInHand", typeof(CashInHandPayment))]
[XmlElementAttribute("CreditCard", typeof(CCPayment))]
[XmlChoiceIdentifierAttribute("ItemElementName")]
[DataMember]
public object Item { get; set; }
}
[DataContract]
public enum ItemElementName
{
[EnumMember]
Account,
[EnumMember]
CashInHand,
[EnumMember]
CreditCard
}
//This class will not be in the generated proxy class
[DataContract]
public class AccountPayment
{
[DataMember]
public double Amount { get; set; }
}
//classes for CashInHandPayment and CCPayment also created, but not shown.
如果“序列化”不是正确使用的术语,请原谅我,如果您阅读问题并发现它不是,请相应地更改它!
更新 - Simon Svensson 提到的答案:
[KnownType(typeof(AccountPayment))]
[KnownType(typeof(CashInHandPayment))]
[KnownType(typeof(CCPayment))]
[DataContract]
public class Payment
{
[XmlElementAttribute("Account", typeof(AccountPayment))]
[XmlElementAttribute("CashInHand", typeof(CashInHandPayment))]
[XmlElementAttribute("CreditCard", typeof(CCPayment))]
[XmlChoiceIdentifierAttribute("ItemElementName")]
[DataMember]
public object Item { get; set; }
}
非常感谢,西蒙!
【问题讨论】:
-
嗨,丹 :),西蒙似乎在下面有正确的想法。 KnownType 属性意味着您的付款类型将在反序列化时得到解决。
-
你好,马克!我希望你很好!是的,KnownType 是我忽略的东西。它需要应用到的不是类本身,而是任何使用它的类,这对我来说似乎有点倒退!