DataContractSerializer和已知类型

时间:2012-02-23 22:48:04

标签: c# serialization datacontractserializer

我在代码中序列化一个对象(不是通过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);

1 个答案:

答案 0 :(得分: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();
}