【问题标题】:C# Inheriting DataContract Derived TypesC# 继承 DataContract 派生类型
【发布时间】:2010-05-20 17:44:37
【问题描述】:

我已经通过 msdn:datacontracts 进行了公平的阅读,但我无法找出以下内容不起作用的原因。 那么这里出了什么问题? 为什么 Datacontract 序列化程序无法识别 ExtendedCanadianAddress?

不应使用数据合同名称“CanadianAddress:http://tempuri.org/Common/Types”键入“XYZ.ExtendedCanadianAddress”。 将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用 KnownTypeAttribute 属性或将它们添加到传递给 DataContractSerializer 的已知类型列表中。

给定:

namespace ABC  
{  
 [KnownType(typeof(Address))] 
 public abstract class Z  
 {
   //stuff
   //method that adds all types() in namespace to self
 }

 [KnownType(typeof(CanadianAddress))]  
 [DataContract(Name = "Address", Namespace = "http://tempuri.org/Types")]  
 public class Address : Z
 {}

 [DataContract(Name = "CanadianAddress", Namespace = "http://tempuri.org/Types")]
 public class CanadianAddress : Address
 {}
}

namespace XYZ
{
 [KnownType(typeof(ExtendedCanadianAddress))
 [DataContract(Name = "Address", Namespace = "http://tempuri.org/Types")] 
 public class ExtendedAddress : Address
 {
   //this serializes just fine
 }
 [DataContract(Name = "CanadianAddress", Namespace = "http://tempuri.org/Types")] 
 public class ExtendedCanadianAddress : CanadianAddress
 {
   //will NOT serialize
 }
}

【问题讨论】:

    标签: c# wcf datacontractserializer datacontract


    【解决方案1】:

    我会尝试复制,但马上属性看起来不对...

    [DataContact] vs [DataContract] 注意缺少的“r”

    此外,尽管您的 c# 命名空间不同,但您的 DataContract 命名空间是相同的,并且您有多个同名合同

    Name = "CanadianAddress", Namespace = "http://tempuri.org/Types"

    【讨论】:

    • 我拥有的是命名空间 ABC 中的最终合同,并在 XYZ 中重新包装了合同,以使用备用构造函数包装 ABC 的合同。我正在尝试通过使用继承来减少代码。
    • 继承没问题,但每个已知的实现必须有一个唯一的Name 或驻留在唯一的Namespace 中。否则无法将请求与正确的具体实现相匹配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    相关资源
    最近更新 更多