2012-02-23 91 views
2

我在代碼中序列化一個對象(而不是通過WCF調用),並且我得到了一些已知類型的掛斷(我已經將它們與WCF一起使用,但不使用DataContract序列化程序作爲「獨立「串行器)DataContractSerializer和已知類型

我運行下面的代碼時出現異常。我預計它運行時沒有錯誤,因爲我提供了已知類型。我在這裏弄錯了什麼?

 

public class Parent {} 
public class Child: Parent {} 

// the code -- serialized is a serialized Child 
// type is typeof(Parent) (I know it works if I pass typeof(Child), but isn't that what Known Types is all about?? 

// passing the known types seems to make no difference -- this only works if I pass typeof(Child) as the first param 
var serializer = new DataContractSerializer(parentType, new Type[] {typeof(Child)}); 
object test = serializer.ReadObject(serialized); 
 
+0

'我得到一個異常'例如? – 2012-02-23 22:49:45

+0

SerializationException:「期望元素'父'...遇到名爲'小孩'的'元素'... – JMarsch 2012-02-23 22:51:51

回答

11

好了,所以我在那些日子裏,我不斷回答自己一個。問題不在於反序列化,而在於序列化 - 您必須使用與反序列化器相同的基本類型創建序列化程序(我已經基於子類型創建了序列化程序)。對於它的價值,工作代碼如下:

 

{ 
      var child = new Child(); 
      // here is where I went wrong before -- I used typeof(Child), with no known types to serialize 
      var serializer = new DataContractSerializer(typeof(Parent), new Type[] { typeof(Child) }); 
      var stream = new MemoryStream(); 
      serializer.WriteObject(stream, child); 
      stream.Position = 0; 
      serializer = new DataContractSerializer(typeof(Parent), new Type[] { typeof(Child) }); 
      object test = serializer.ReadObject(stream); 
      stream.Dispose(); 
      Console.WriteLine(test.ToString()); 
      Console.ReadLine(); 
} 
 
相關問題