2012-02-23 48 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(); 
} 
 
相关问题