我有这些课:

[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 {}


在此blog中了解有关KnownType属性的更多信息

10-06 13:27