我知道已经有很多关于该主题的讨论,例如:
BinaryFormatter 和反序列化复杂对象 https://stackoverflow.com/questions/5017274/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>
和第二个元素aDictionary<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
}
}
你可以尝试一下在这个小提琴上 https://dotnetfiddle.net/uPZ1HN.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)