gpt4 book ai didi

c# - 使用 BinaryFormatter 序列化和反序列化 List>

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

假设我有

List<object> mainList = new List<object>();

它包含

List<string> stringList = new List<string();
List<CustomClass> custList = new List<CustomClass>();
mainList.Add(stringList);
mainList.Add(custList);

序列化

Stream stream;
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, mainList);

反序列化

Stream stream = (Stream)o;
BinaryFormatter formatter = new BinaryFormatter();
List<object> retrievedList = (List<object>)formatter.Deserialize(stream);

此时,我收到一个错误,指出流读取(反序列化)已到达流的末尾,但未检索到值。

除了...我还需要指定一些东西吗

[Serializable]
public class CustomClass { .... }

在自定义类中使其工作?我可以不反序列化一个 List> 每次都包含不同类型的对象吗?

我试过了

IList list = (IList)Activator.CreateInstance(typeof(custClassList[0]))

并尝试发送和接收这个,但遇到了同样的问题。

不过,我可以序列化和反序列化指定的类型或列表,但我确实需要它是动态的。

最佳答案

基本上,BinaryFormatter 就是个笑话。它在某些情况下有效,但由于未知原因在几乎相同的情况下会失败。

BinaryFormatter 的最佳替代品是第三方库 protobuf-net ( https://github.com/mgravell/protobuf-net ),由 Marc Gravel 开发.

这个美女一下子解决了我遇到的所有问题。设置起来更容易,对复杂的自定义类的 react 也更完美。

我还应该提到它在反序列化方面更快。

关于c# - 使用 BinaryFormatter 序列化和反序列化 List<List<object>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18876229/

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