我有这些课程:
[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 的实例,我会在序列化期间收到服务端异常:
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) 对象。
我有一大堆错误类型,列表将包含它们的组合,那么我该怎么做才能使它工作呢?
您应该将 KnownType 属性添加到您的基类中
[DataContract]
[KnownType(typeof(FileMissingError))]
public class ErrorBase {}
阅读有关 KnownType 属性的更多信息blog http://blogs.msdn.com/sowmy/archive/2006/06/06/all-about-knowntypes.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)