WCF - 序列化继承的类型 [英] WCF - serializing inherited types

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

问题描述

我有这些课程:

[DataContract]
public class ErrorBase {}

[DataContract]
public class FileMissingError: ErrorBase {}

[DataContract]
public class ResponseFileInquiry
{
  [DataMember]
  public List<ErrorBase> errors {get;set;};
}

ResponseFileInquiry 类的一个实例是我的服务方法返回给客户端的.现在,如果我用 ErrorBase 的实例填充 ResponseFileInquiry.errors,一切正常,但如果我添加一个继承类型 FileMissingError 的实例,我会在序列化期间收到服务端异常:

An instance of the class ResponseFileInquiry is what my service method returns to the client. Now, if I fill ResponseFileInquiry.errors with instances of ErrorBase, everything works fine, but if I add an instance of inherited type FileMissingError, I get a service side exception during serialization:

Type 'MyNamespace.FileMissingError' with data contract name 'FileMissingError' 
is not expected. Add any types not known statically to the list of known types - 
for example, by using the KnownTypeAttribute attribute or by adding them to the 
list of known types passed to DataContractSerializer.'

因此序列化程序变得困惑,因为它期望 List 包含声明的类型对象 (ErrorBase),但它正在获取继承的类型 (FileMissingError) 对象.

So serializer is getting confused because it's expecting the List to contain the declared type objects (ErrorBase) but it's getting inherited type (FileMissingError) objects.

我有一大堆错误类型,列表将包含它们的组合,那么我该怎么做才能使它工作?

I have the whole bunch of error types and the List will contain combinations of them, so what can I do to make it work?

推荐答案

你应该在你的基类中添加KnownType属性

You should add KnownType attribute to your base class

[DataContract]
[KnownType(typeof(FileMissingError))]
public class ErrorBase {}

在此博客中阅读有关KnownType 属性的更多信息

这篇关于WCF - 序列化继承的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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