问题
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