我知道已经有很多关于该主题的讨论,例如:
但这看起来非常复杂。我正在寻找一种更简单的方法来将通用对象列表序列化到一个文件中或从一个文件中反序列化。这是我尝试过的:
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 …Run Code Online (Sandbox Code Playgroud) 我有一个让我疯狂的问题.我正在使用一个泛型List,每当我尝试将其第一个(或最后一个?)索引分配给变量时,它会抛出ArgumentOutOfRangeException.这是一大堆代码,因此我将尝试仅提取相关内容.所以这里是:
private string GetRuleByName(string name, List<string> rules)
{
if(rules != null)
{
List<string> todo = new List<string>();
todo.AddRange(rules);
while(rules.Count != 0)
{
string r = todo[0]; // <- Error 'ArgumentOutOfRangeException' here
todo.RemoveAt(0);
// ...
}
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我称之为方法的方式:
void treeView_AfterSelect(object sender, TreeViewEventArgs e)
{
string currentRule = GetRuleByName(treeView.SelectedNode.FullPath, ruleCollection)
// the string list "ruleCollection" always contains
// strings and thus is never empty
}
Run Code Online (Sandbox Code Playgroud)
虽然它不是一个非常详细的介绍正在发生的事情,因为我不得不切断一些复杂的代码,我真的希望别人可能会看到产生错误的原因.
非常感谢提前至少看看!
编辑:
这就是方法的样子.我没有改变任何东西,以显示其中的真实内容.我希望对某些人有意义:
private Rule GetRuleByNameOrId(string stName, List<Rule> rules)
{
if(rules != null)
{ …Run Code Online (Sandbox Code Playgroud)