我正在代码中序列化一个对象(不是通过 WCF 调用),并且我对已知类型有点沉迷(我已将它们与 WCF 一起使用,但没有将 DataContract 序列化器作为“独立”序列化器使用)
当我运行下面的代码时出现异常。我希望它运行时不会出现错误,因为我提供了已知类型。我在这里犯了什么错?
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);
好吧,我正经历着不断回答自己问题的日子。问题不在于反序列化,而在于序列化——您必须创建与反序列化器具有相同基本类型的序列化器(我已经根据子类型创建了序列化器)。就其价值而言,工作代码如下:
{
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)