c# - 使用 BinaryFormatter 序列化/反序列化对象列表

标签 c# object serialization deserialization binaryformatter

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

BinaryFormatter and Deserialization Complex objects

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

    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。有谁知道如何将字典和树节点拉出来并将它们投回去,可能采用不同的方法,但也很简单?谢谢!

最佳答案

您已经序列化了一个对象列表,其中第一项是节点列表,第二项是字典。所以当反序列化时,你会得到相同的对象。

反序列化的结果将是 List<object> ,其中第一个元素是 List<TreeNode>第二个元素a 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
    }
}

你可以试一试on this fiddle .

关于c# - 使用 BinaryFormatter 序列化/反序列化对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26383711/

相关文章:

php - 无法从数据库检索序列化数据

c# - 在 C# 中设计比特流

c# - 使用 SqlFileStream 从 WCF 服务返回流

javascript - 有什么是 Object.create() 可以做但工厂函数不能做的事情吗?

java - 面向对象的 Java 点和方法继承

c++ - 在 C++ 中使用 BOOST 序列化循环图

c# - 将 XmlRoot 或 XmlType 与 RestSharp 结合使用

c# - 选择一个*启发式函数

c# - 我可以在 Ruby/Java/C# 中创建这样的对象吗?

javascript - 全局对象属性修改可以从函数中进行,但不能重新定义对象本身