使用二进制格式化程序对对象列表进行序列化/反序列化

5

我知道这个话题已经有很多讨论了,比如这个:

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>>>;

        }
    }

序列化可以正常工作,但反序列化失败并出现了ArgumentNullException异常。有没有人知道如何取出字典和树节点并进行转换,可能需要采用不同的方法,但也要简单易懂?谢谢!

是的,看起来'obj'确实是空的,但在我这个血腥初学者的眼里,它并不是。:-S - betaFlux
1个回答

4
您已经对一个对象列表进行了序列化,其中第一个项目是节点列表,第二个项目是字典。因此,在反序列化时,您将获得相同的对象。
反序列化的结果将是一个 List<object>,其中第一个元素是一个 List<TreeNode>,第二个元素是一个 Dictionary<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
    }
}

您可以在这个代码编辑器中试一试。

1
太棒了,现在它完美地运行了。看来我应该学习一些格式化工具的知识。感谢您的修订!顺便说一下:这是一个很棒的工具! - betaFlux
很高兴能帮忙!(我真的很喜欢dotnetfiddle) - Daniel J.G.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接