所以我有一个可序列化的类Student,我想让我的ReadFromFile方法反序列化文件,这样我就可以知道我已经在对象中有多少条记录,这样当我想要向数组添加新记录时,我就可以知道最后一个数组的索引是什么,并且我可以把我的新记录放在那之后的索引号。在第二个传递“
Console.WriteLine(st2[j].FName + " "+st2[j].LName);
”时,该函数会报错,并告诉我:
它只会写入我所拥有的记录中的第一项,而不是其余的记录。NullReferenceException未被处理
public static int ReadFromFile()
{
int j = 0;
string path = @"students.dat";
try
{
Students[] st2 = new Students[100];
BinaryFormatter reader = new BinaryFormatter();
FileStream input = new FileStream(path, FileMode.Open, FileAccess.Read);
st2 = (Students[])reader.Deserialize(input);
while (true)
{
st[j] = new Students();
Console.WriteLine(st2[j].FName + " " + st2[j].LName);
j++;
}
Console.WriteLine("there are " + j + "students in the file");
input.Close();
return j;
}
catch (FileNotFoundException)
{
Console.WriteLine("there are no student records yet.");
return j;
}
}
这是我的序列化方法:
public static void WriteInFileFromInput(Students[] x)
{
string path = @"students.dat";
if (File.Exists(path))
{
BinaryFormatter Formatter = new BinaryFormatter();
FileStream output = new FileStream(path, FileMode.Append, FileAccess.Write);
Formatter.Serialize(output, st);
output.Close();
}
else
{
BinaryFormatter Formatter = new BinaryFormatter();
FileStream output = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
Formatter.Serialize(output, st);
output.Close();
}
}
FileStream
放在using
块中:using (FileStream output = new FileStream(...)){...}
。即使出现异常,它也会进行清理。 - John Saunderswhile(true) { }
循环无限期地执行,除非出现异常(NullReferenceException,IndexOutOfRangeException)。 - JeffRSonFormatter.Serialize(output, st);
-st
是从哪里来的? - Matthew Watsonpublic static Students[] st = new Students[100]
,并且我有一个Write()函数,用于将学生信息写入对象数组中。然后该对象被序列化在WriteInFileFromInput中写入文件。 - Lily