我有这些课程:
[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)对象。
我有一大堆错误类型,列表将包含它们的组合,那么我该怎么做才能让它工作呢?