Guessing Object Type while Deserializing
I have a few objects serialized [edit: using BinaryFormatter] this way
Obj_A 1
Obj_A 2
Obj_A 3
Obj_B 1
Obj_B 2
Obj_B 3
Obj_B 4
开发者_如何学运维How many A objects there are before B's is decided by user on Runtime.
While deserializing, I have no way to guess when to switch form Obj_A deseriliazing to Obj_B
I welcome any relevant insight
EDIT : Serialization occurs on the flow and numbers of A's and B's is not known beforehand
ANSWER
Marc Gravell suggested something I was JUST NOT aware of : Why bother at all ? Just let the formatter do the job and test types afterwards. (I am surprised I was not massively aswered that by people here, so obvious...)IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("X:\\binary.dump", FileMode.Open);
object o = formatter.Deserialize(stream);
if (o.GetType() == typeof(Obj_A))
ReadTheMSDN(Obj_A);
else if (o.GetType() == typeof(Obj_B))
KnowObjectsYouHandle(Obj_B);
stream.Close();
Another less elegant solution was to force objects to Lists :
LIST Obj_A
Obj_A 1
Obj_A 2
Obj_A 3
LIST Obj_B
Obj_B 1
Obj_B 2
Obj_B 3
Obj_B 4
What serialisation are you using? Various options
- use a serialiser that handles this for you
- use something before each that tells you the type that follows (could be the full type, could be some marker code, or could be the element name (XML), member-name (JSON), etc)
- write the number if A before the As, the number of B before the Bs etc
- if using something like BinaryFormatter or NetDataContractSerializer (which both include type metadata), deserialize it as normal and use GetType() afterwards to find what you were given
精彩评论