在我的Silverlight 4应用程序中,我使用DataContractSerializer对数据进行序列化/反序列化。我可以有两种不同类型的数据:EditorModel和ConfiguratorModel。两个模型都继承自一个共同的基类。
[DataContract(IsReference = true, Name = "ServiceModel", Namespace = "ServiceModeller.DataModel.Serialization")]
[KnownType(typeof(DTO_ServiceModelEditor))]
[KnownType(typeof(DTO_ServiceModelConfigurator))]
public abstract class DTO_ServiceModelBase { ... }
[DataContract(IsReference = true, Name = "ServiceModelEditor", Namespace = "ServiceModeller.DataModel.Serialization")]
public class DTO_ServiceModelEditor : DTO_ServiceModelBase { ... }
[DataContract(IsReference = true, Name = "ServiceModelConfigurator", Namespace = "ServiceModeller.DataModel.Serialization")]
public class DTO_ServiceModelConfigurator : DTO_ServiceModelBase { ... }
序列化没有问题,并按预期工作。当我反序列化时,我不想命名特定的继承类,因为用户也可以加载EditorModel或ConfiguratorModel。我找到了this stackoverflowquestion,由Marc Gravell回答,据我所知,我可以在知道继承类型时使用基类(它可以使用它,参见DTO_ServiceModelBase中的KnownType-Declaration)。
但是,当我执行以下反序列化时(我还添加了两个继承类型作为第二个参数):
DataContractSerializer serializer = new DataContractSerializer(typeof(DTO_ServiceModelBase), new Type[] {typeof(DTO_ServiceModelEditor), typeof(DTO_ServiceModelConfigurator)} );
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new System.IO.StringReader(stream));
// stream is the serialized string
object result;
try
{
result = serializer.ReadObject(reader);
}
catch (Exception ex)
{ .. }
它会引发异常,因为它需要“ServiceModel”但却找到了“ServiceModelEditor”。有什么我忘了,或者我的Marc答案错了吗?
提前致谢,
弗兰克
答案 0 :(得分:5)
你是如何进行序列化的?当你序列化时,你必须指定你正在写出基类DTO_ServiceModelBase的对象,然后它应该工作。因此,当您进行序列化时,只需按照反序列化示例中的方式定义DataContractSerialiser:
DataContractSerializer serializer = new DataContractSerializer(typeof(DTO_ServiceModelBase), new Type[] {typeof(DTO_ServiceModelEditor), typeof(DTO_ServiceModelConfigurator)} );
从错误中看起来好像你做了类似的事情:
DataContractSerializer serializer = new DataContractSerializer(typeof(DTO_ServiceModelEditor));