DataContract和继承? [英] DataContract and inheritance?

查看:71
本文介绍了DataContract和继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在继承中使用DataContract?下面的代码会起作用吗?

How to use DataContract with inheritance? Will code below work?

[DataContract]
public class ConsoleData
{
    [DataMember]
    public String Description { get; set; }

}

[DataContract]
public class SomeData : ConsoleData
{

    [DataMember]
    public int Volume { get; set; }
    ......


推荐答案

是的,那会起作用。

DataContractAttribute 具有 Inherited 设置为false,因此有必要将属性同时应用于子类和父类(如您在问题中所做的那样。)。

The DataContractAttribute has Inherited set to false, so it is necessary to apply the attribute to both the child class and the parent class (as you have done in the question).



如果要使用具有多态性的数据合同,则需要使用 KnownType 属性。

例如

 [ServiceContract]
 interface MyWcfContract
 {
       [OperationContract]
       HandleData(ConsoleData contractData);
 }

如果您这样调用方法:

 SomeData someData = new SomeData { Description = "Test", Volume = 30 };
 // The method is expecting a ConsoleData instance, 
 // I'm passing a SomeData instance instead
 myWcfProxy.HandleData(someData);

然后,服务端的反序列化器将不知道它是的实例SomeData ,只是它期望的 ConsoleData 的一个实例。
解决此问题的方法是将 SomeData 类注册为 ConsoleData 的已知类型。 / p>

Then the deserializer on the service end will not know that it's an instance of SomeData, just an instance of ConsoleData which it was expecting. The way to fix this is to register the SomeData class as a known type of the ConsoleData.

[DataContract]
[KnownType(typeof(SomeData))]
public class ConsoleData
{
    [DataMember]
    public String Description { get; set; }

}

[DataContract]
public class SomeData : ConsoleData
{

    [DataMember]
    public int Volume { get; set; }
    ......

这篇关于DataContract和继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆