编程语言
首页 > 编程语言> > c#-使用BinaryFormatter序列化和反序列化List>

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

作者:互联网

假设我有

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 { .... }

在自定义类中使这项工作?我可以不反序列化列表吗?每次包含不同类型的对象?

我试过了

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

并尝试发送和接收此邮件,但遇到了同样的问题.

但是,我可以序列化和反序列化指定的类型或列表,但是我真的需要它是动态的.

解决方法:

基本上,BinaryFormatter是个玩笑.它在某些情况下可以工作,但由于未知原因,在几乎相同的情况下将失败.

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

这位美女一口气解决了我遇到的所有问题.设置起来更容易,并且可以对复杂的自定义类做出更完美的反应.

我还应该提到,就反序列化而言,它的速度更快.

标签:serialization,deserialization,stream,binaryformatter,c
来源: https://codeday.me/bug/20191030/1967643.html