使用BinaryFormatter序列化/反序列化对象列表 [英] serialize/deserialize a list of objects using BinaryFormatter
问题描述
我知道关于该主题的讨论已经很多,就像这样:
I know there were already many discussions on that topic, like this one:
但是这看起来非常复杂.我正在寻找一种更简单的方法来将一个对象的通用列表序列化和反序列化到一个文件中或从一个文件中反序列化.这是我尝试过的:
but this looks awfully complicated. What I'm looking for is an easier way to serialize and deserialize a generic List of objects into/from one file. This is what I've tried:
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.有谁知道如何拉出字典和树节点并将其抛回去,也许采用了不同的方法,但是又很好又简单?谢谢!
The serialization works, but the deserialization fails with an ArgumentNullException. Does anyone know how to pull the dictionary and the tree nodes out and cast them back, may be with a different approach, but also nice and simple? Thanks!
推荐答案
您已序列化了对象列表,其中第一项是节点列表,第二项是字典.因此,在反序列化时,您将获得相同的对象.
You have serialized a list of objects where the first item is a list of nodes and the second a dictionary. So when deserializing, you will get the same objects back.
反序列化的结果将是List<object>
,其中第一个元素是List<TreeNode>
,第二个元素是Dictionary<int, Tuple<List<string>, List<string>>>
The result from deserializing will be a List<object>
, where the first element is a List<TreeNode>
and the second element 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
}
}
您可以尝试在这个小提琴上.
这篇关于使用BinaryFormatter序列化/反序列化对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!