使用 BinaryFormatter 序列化/反序列化对象列表

bet*_*lux 5 c# serialization object binaryformatter deserialization

我知道已经有很多关于该主题的讨论,例如:

BinaryFormatter 和反序列化复杂对象

但这看起来非常复杂。我正在寻找一种更简单的方法来将通用对象列表序列化到一个文件中或从一个文件中反序列化。这是我尝试过的:

    public void SaveFile(string fileName)
    {
        List<object> objects = new List<object>();

        // Add all tree nodes
        objects.Add(treeView.Nodes.Cast<TreeNode>().ToList());

        // Add dictionary (Type: Dictionary<int, Tuple<List<string>, List<string>>>)
        objects.Add(dictionary);

        using(Stream file = File.Open(fileName, FileMode.Create))
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(file, objects);
        }
    }

    public void LoadFile(string fileName)
    {
        ClearAll();
        using(Stream file = File.Open(fileName, FileMode.Open))
        {
            BinaryFormatter bf = new BinaryFormatter();

            object obj = bf.Deserialize(file);

            // Error: ArgumentNullException in System.Core.dll
            TreeNode[] nodeList = (obj as IEnumerable<TreeNode>).ToArray();

            treeView.Nodes.AddRange(nodeList);

            dictionary = obj as Dictionary<int, Tuple<List<string>, List<string>>>;

        }
    }
Run Code Online (Sandbox Code Playgroud)

序列化有效,但反序列化失败并出现 ArgumentNullException。有谁知道如何将字典和树节点拉出来并将它们投射回来,可能采用不同的方法,但也很好很简单?谢谢!

Dan*_*.G. 4

您已经序列化了一个对象列表,其中第一项是节点列表,第二项是字典。因此,反序列化时,您将得到相同的对象。

反序列化的结果将是 a List<object>,其中第一个元素是 a List<TreeNode>,第二个元素是 aDictionary<int, Tuple<List<string>, List<string>>>

像这样的东西:

public static void LoadFile(string fileName)
{
    ClearAll();
    using(Stream file = File.Open(fileName, FileMode.Open))
    {
        BinaryFormatter bf = new BinaryFormatter();

        object obj = bf.Deserialize(file);

        var objects  = obj as List<object>;
        //you may want to run some checks (objects is not null and contains 2 elements for example)
        var nodes = objects[0] as List<TreeNode>;
        var dictionary = objects[1] as Dictionary<int, Tuple<List<string>,List<string>>>;
        
        //use nodes and dictionary
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以尝试一下这个小提琴