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

查看:17
本文介绍了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);
 }

如果你像这样调用方法:

If you invoked the method like so:

 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 的已知类型.

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天全站免登陆