【发布时间】: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