【问题标题】:Force WCF to serialize unused class强制 WCF 序列化未使用的类
【发布时间】: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 是我忽略的东西。它需要应用到的不是类本身,而是任何使用它的类,这对我来说似乎有点倒退!

标签: c# xml wcf


【解决方案1】:

嗯。不是 XmlElementAttribute 和 XmlChoiceIdentifierAttribute xml 序列化,与读取 DataContractAttribute 和 DataMemberAttribute 的 DataContractSerializer 相比,它是一种较旧的序列化?

我认为您应该为此使用 KnownTypeAttribute,但我从未尝试过,我自己的代码中也没有这种情况。

【讨论】:

  • 是的,你是对的,它是旧序列化的一部分(来自原始 XSD)。要将它们拉入代理类,我必须将 KnownType 应用于 Payment 类。非常感谢!
【解决方案2】:

有什么方法可以强制诸如AccountPayment之类的类, CashInHandPayment 和 CCPayment 要在代理类中序列化?

它们需要用[DataContract] 属性标记,我认为这应该足够了。

svcutil.exe(直接从命令行启动,或使用Add Service Reference 从Visual Studio 启动)遇到类上具有[DataContract] 属性和属性(或字段)上具有[DataMember] 的类时,它将在代理中为这些类创建一个副本。

马克

【讨论】:

  • Marc,如以 AccountPayment 为例的代码所示,类设置了 DataContractAttribute。
【解决方案3】:

我认为指定 DataContract 就足够了。但是,如果这不起作用,为什么不尝试创建一个使用该类的虚拟 OperationContract 方法?

【讨论】:

  • 这将是我最后的手段,因为我知道它会起作用,而且我知道它是令人难以置信的 hacky。 :) 我确实同意 DataContract 应该足够了,但似乎如果您创建一个引用您使用的大多数类的服务,则在生成代理时,它会忽略未使用的那些,即使您将 DataContract 应用于所有其中。
猜你喜欢
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多