DataContractSerializer and Known Types

人走茶凉 提交于 2019-12-10 21:34:10

问题


I am serializing an object in code (not via a WCF call), and I am getting a little hung up with known types (I have used them with WCF, but not with the DataContract serializer as a "stand-alone" serializer)

I get an exception when I run the code below. I expected it to run without error because I supplied Known Types. What am I getting wrong here?


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:


Ok, so I'm having one of those days where I keep answering myself. The problme was not with the deserialization, it was in the serialization -- you must create the serializer with the same base type as the deserializer (I had created the serializer based upon the child type). For what it's worth, working code is below:


{
            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();
}



来源:https://stackoverflow.com/questions/9422662/datacontractserializer-and-known-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!