【问题标题】:DataContractSerializer and Known TypesDataContractSerializer 和已知类型
【发布时间】:2025-12-31 18:15:02
【问题描述】:

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

【问题讨论】:

  • I get an exception 例如?
  • SerializationException: "期望元素 'Parent' ...遇到名为 'Child' 的 'Element' ...

标签: c# serialization datacontractserializer


【解决方案1】:

好的,所以我有一个我一直在回答自己的日子。问题不在于反序列化,而在于序列化——您必须创建与反序列化器具有相同基本类型的序列化器(我已经根据子类型创建了序列化器)。对于它的价值,工作代码如下:

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

【讨论】: