gpt4 book ai didi

c# - DataContractSerializer 和已知类型

转载 作者:行者123 更新时间:2023-11-30 13:33:09 25 4
gpt4 key购买 nike

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

最佳答案

好吧,我正在度过那些我不断回答自己的日子。问题不在于反序列化,而在于序列化——您必须创建与反序列化器具有相同基类型的序列化器(我已经基于子类型创建了序列化器)。对于它的值(value),工作代码如下:


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

关于c# - DataContractSerializer 和已知类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9422662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com