3

Let's say I have

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

And it contains

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

To serialize

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

To deserialize

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

At this point, I receive an error that the stream read (deserialization) reached the end of the stream without retrieving a value.

Do I need to specify something besides...

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

in the custom class to make this work? Can I not deserialize a List> that contains different type of object every time?

I tried

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

and tried to send and receive this, but got the same issue.

I can however serialize and deserialize a specified type or List, but I really need it to be dynamic.

4

2 回答 2

3

Basically, BinaryFormatter is a joke. It works in some cases, but will fail in almost identical scenarios for unknown reasons.

The best and superior alternative to BinaryFormatter is the third-party library protobuf-net (https://github.com/mgravell/protobuf-net), developed by Marc Gravel.

This beauty solved all the problems I was having in one pass. It's much easier to set up and reacts more perfectly to complex, custom classes.

I should also mention that it's faster, in the terms of de/serialization.

于 2013-09-24T18:40:40.443 回答
1

In order to fix the issue that causes the error "stream read (deserialization) reached the end of the stream ", the stream position needs to reset to 0 as follows...

stream.Position = 0;

Do I need to specify something besides...

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

Nope...That should be good for what you are doing.

in the custom class to make this work? Can I not deserialize a List> that contains different type of object every time?

You should be able to serialize any object.

于 2013-09-18T15:41:19.040 回答