[Serializable] public abstract class ResponseBase { public bool Successful { get; set; } public List<ResponseMessage> Messages { get; set; } //...Other code... }
Messages集合可以是以下任何类型:
[Serializable] [XmlInclude(typeof(DebugMessage))] [XmlInclude(typeof(InfoMessage))] [XmlInclude(typeof(ValidationMessage))] [XmlInclude(typeof(WarnMessage))] [XmlInclude(typeof(RecoverableFaultMessage))] [XmlInclude(typeof(FatalFaultMessage))] public abstract class ResponseMessage { //..Other code... }
具体版本:
[Serializable] public class DebugMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.Debug; } } } [Serializable] public class InfoMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.Info; } } } [Serializable] public class ValidationMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.Validation; } } } [Serializable] public class WarnMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.Warn; } } } [Serializable] public class RecoverableFaultMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.RecoverableFault; } } } [Serializable] public class FatalFaultMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.FatalFault; } } }
所有DTO Response对象都继承自ResponseBase,但即使在WCF契约中使用以下ServiceKnownTypes也是如此
[ServiceKnownType(typeof(ResponseBase))] [ServiceKnownType(typeof(ResponseMessage))] [ServiceKnownType(typeof(List<ResponseMessage>))] [ServiceKnownType(typeof(DebugMessage))] [ServiceKnownType(typeof(InfoMessage))] [ServiceKnownType(typeof(ValidationMessage))] [ServiceKnownType(typeof(WarnMessage))] [ServiceKnownType(typeof(RecoverableFaultMessage))] [ServiceKnownType(typeof(FatalFaultMessage))] [ServiceKnownType(typeof(List<DebugMessage>))] [ServiceKnownType(typeof(List<InfoMessage>))] [ServiceKnownType(typeof(List<ValidationMessage>))] [ServiceKnownType(typeof(List<WarnMessage>))] [ServiceKnownType(typeof(List<RecoverableFaultMessage>))] [ServiceKnownType(typeof(List<FatalFaultMessage>))]
当我们将Message加载到ResponseBase Messages集合时,会抛出以下异常:
Error in line 1 position 906. Element
‘http://schemas.datacontract.org/2004/07/CX.Framework.Common.BaseTypes:ResponseMessage’
contains data from a type that maps to the name
‘http://schemas.datacontract.org/2004/07/CX.Framework.Common.BaseTypes:WarnMessage’.
The deserializer has no knowledge of any type that maps to this name.
Consider using a DataContractResolver or add the type corresponding to
‘WarnMessage’ to the list of known types – for example,by using the
KnownTypeAttribute attribute or by adding it to the list of known
types passed to DataContractSerializer.
我们已经在派生类型上完成了从ServiceKnownType到XMLInclude的所有操作.我对如何解决这个问题感到有点失落,并感谢任何人都能提供的帮助.