我刚刚阅读Serialization/Deserialization
并BinaryFormatter (SoapFormatter)
编写了一些代码来检查此过程的行为:
class Program
{
private static List<string> listA = new List<string>() { "ListA-0", "ListA-1" };
private static List<string> listB = new List<string>() { "ListB-0", "ListB-1" };
private static List<string> listC = new List<string>() { "ListC-0", "ListC-1" };
private static void SaveApplicationState(Stream stream)
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, listA);
formatter.Serialize(stream, listB);
formatter.Serialize(stream, listC);
}
private static void LoadApplicationState(Stream stream)
{
BinaryFormatter formatter = new BinaryFormatter();
listA = (List<string>)formatter.Deserialize(stream);
listB = (List<string>)formatter.Deserialize(stream);
listC = (List<string>)formatter.Deserialize(stream);
}
private static void ShowList(string msg)
{
Console.WriteLine(msg);
foreach (var str in listA.Union(listB).Union(listC))
Console.WriteLine(str);
}
static void Main(string[] args)
{
using (MemoryStream ms = new MemoryStream())
{
ShowList("Before save: ");
SaveApplicationState(ms);
ms.Position = 0;
LoadApplicationState(ms);
ShowList("After load: ");
}
}
}
两个结果相似并且(反序列化对象的顺序):
Before save:
ListA-0
ListA-1
ListB-0
ListB-1
ListC-0
ListC-1
After load:
ListA-0
ListA-1
ListB-0
ListB-1
ListC-0
ListC-1
但是我对这种行为有疑问(如果它是愚蠢的或不正确的,很抱歉)。
如果我添加新的List<int>
:
private static List<int> list0 = new List<int>() { 1, 2 };
它Serialize
在开始时Stream
:
formatter.Serialize(stream, list0);
formatter.Serialize(stream, listA);
formatter.Serialize(stream, listB);
formatter.Serialize(stream, listC);
但尝试Deserialize
使用错误的顺序:
listA = (List<string>)formatter.Deserialize(stream);
list0 = (List<int>)formatter.Deserialize(stream);
listB = (List<string>)formatter.Deserialize(stream);
listC = (List<string>)formatter.Deserialize(stream);
我会例外,casting
我明白为什么会这样。
那么,是否可以从中获取特定对象Stream
(例如,如果我知道这个type
或任何其他对象properties
)或者我必须Deserialize
流式传输直到结束并按顺序获取每个对象Serialized
?