我知道已经有很多关于这个话题的讨论,比如这个:
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/