2011-12-02 56 views
6

我使用DataContractSerializer序列化/反序列化數據。我可以有兩種不同類型的數據:EditorModel和ConfiguratorModel。這兩種模型都從一個通用的基類繼承而來。在我的Silverlight 4應用程序中,使用DataContractSerializer(typeof(BaseClass))Deserialize繼承的類

[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」。有什麼我忘記了,還是我的馬克答案錯了?

由於提前,
弗蘭克

回答

5

你怎麼樣序列化?在序列化時,必須指定寫出基類DTO_ServiceModelBase的對象,然後才能正常工作。因此,當你剛剛串行化定義DataContractSerialiser相同的方式,在您的deserialisation例如:

DataContractSerializer serializer = new DataContractSerializer(typeof(DTO_ServiceModelBase), new Type[] {typeof(DTO_ServiceModelEditor), typeof(DTO_ServiceModelConfigurator)}); 

從錯誤看起來好像你做了這樣的事情,而不是:

DataContractSerializer serializer = new DataContractSerializer(typeof(DTO_ServiceModelEditor)); 
+1

這應該已被標記爲正確的答案。 –

相關問題