序列化和反序列化List <list <object>&gt;使用BinaryFormatter </list <object>

时间:2013-09-18 15:21:13

标签: c# serialization stream deserialization binaryformatter

假设我有

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&gt;每次包含不同类型的对象?

我试过

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

并尝试发送和接收此内容,但遇到了同样的问题。

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

2 个答案:

答案 0 :(得分:3)

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

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

这个美女一次性解决了我遇到的所有问题。设置和更复杂地对复杂的自定义类做出反应要容易得多。

我还应该提到它在de / serialization方面更快。

答案 1 :(得分:1)

为了解决导致错误“流读取(反序列化)到达流的末尾”的问题,流位置需要重置为0,如下所示...

stream.Position = 0;
  

我是否需要指定除......之外的其他内容。

     

[Serializable]公共类CustomClass {....}

不......那应该对你正在做的事情有好处。

  

在自定义类中使这个工作?我可以不反序列化List&gt;   每次包含不同类型的对象?

您应该能够序列化任何对象。