二进制反序列化中的NullReferenceException

3
所以我有一个可序列化的类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();
        }
    }

你使用数组Students[]而不是动态集合(如Collection<Student>)的原因是什么? - Ondrej Svejdar
我会将 FileStream 放在 using 块中:using (FileStream output = new FileStream(...)){...}。即使出现异常,它也会进行清理。 - John Saunders
while(true) { } 循环无限期地执行,除非出现异常(NullReferenceException,IndexOutOfRangeException)。 - JeffRSon
Formatter.Serialize(output, st); - st 是从哪里来的? - Matthew Watson
我在类的开头定义了public static Students[] st = new Students[100],并且我有一个Write()函数,用于将学生信息写入对象数组中。然后该对象被序列化在WriteInFileFromInput中写入文件。 - Lily
显示剩余2条评论
1个回答

0
正确的循环应该像这样(假设数据已经正确序列化):
foreach (var student in st2) // Replaces the while loop in the OP
{
    Console.WriteLine(student.FName + " " + student.LName);
    ++j;
}

然而,我认为序列化中存在错误,因此仍会导致空引用异常。 如果是这样,请您发布序列化数据的代码?


很遗憾,那并没有解决它。我已经使用序列化函数编辑了帖子。 - Lily
我在序列化函数之外改了一些东西,现在我的数组中可以有所有的记录,但是我仍然得到相同的错误,显然因为我现在的数组仍然有98个记录的位置。这是问题吗? - Lily

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接