如何使用反序列化从Stream中获取特定对象

时间:2013-07-30 11:10:21

标签: c# .net serialization deserialization

我刚刚用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

0 个答案:

没有答案