【问题标题】:serialize/deserialize a list of objects using BinaryFormatter使用 BinaryFormatter 序列化/反序列化对象列表
【发布时间】:2014-12-10 14:22:14
【问题描述】:

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

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

【问题讨论】:

  • 是的,'obj' 似乎确实为空,但在我的血腥初学者看来,它不是。 :-S

标签: c# object serialization deserialization binaryformatter


【解决方案1】:

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

反序列化的结果将是List&lt;object&gt;,其中第一个元素是List&lt;TreeNode&gt;,第二个元素是Dictionary&lt;int, Tuple&lt;List&lt;string&gt;, List&lt;string&gt;&gt;&gt;

类似这样的:

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

【讨论】:

  • 太棒了,现在它可以完美运行了。似乎我应该获得一些关于格式化程序如何工作的知识。感谢您的修订!顺便说一句:很棒的工具!
  • 很高兴为您提供帮助! (我真的很喜欢 dotnetfiddle)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
  • 2012-08-12
  • 2015-01-15
  • 1970-01-01
相关资源
最近更新 更多