C# 空引用异常和流读取器

本文关键字:读取 异常 引用 | 更新日期: 2023-09-27 18:36:36

从我的 txt 文件中读取数据时出现空引用异常。

     public class Appointments : List<Appointment>
        {
            Appointment appointment;
            public Appointments()
            {
            }
            public bool Load(string fileName)
            {
                string appointmentData = string.Empty;
                using (StreamReader reader = new StreamReader(fileName))
                {
                    while((appointmentData = reader.ReadLine()) != null)
                    {
                        appointmentData = reader.ReadLine();
                        //**this is where null ref. exception is thrown** (line below)
                        if(appointmentData[0] == 'R')
                        {
                            appointment = new RecurringAppointment(appointmentData);
                        }
                        else
                        {
                            appointment = new Appointment(appointmentData);
                        }
                        this.Add(appointment);
                    }
                    return true;
                }
            }

RecurringAppointment继承自Appointments .文件存在,文件位置正确。有趣的是,该程序在 30 分钟前仍在工作,我只将下面的加载方法更改为您在上面看到的内容:

 public bool Load(string fileName)
        {
            string appointmentData = string.Empty;
            using (StreamReader reader = new StreamReader(fileName))
            {
                while((appointmentData = reader.ReadLine()) != null)
                {
                    appointmentData = reader.ReadLine();
                    if(appointmentData[0] == 'R')
                    {
                        this.Add(appointment = new RecurringAppointment(appointmentData));
                    }
                    else
                    {
                        this.Add(appointment = new Appointment(appointmentData));
                    }
                }
                return true;
            }
        }

现在它在这两种情况下都不起作用。

C# 空引用异常和流读取器

您的代码在每个循环中读取两次。这意味着,如果在读取文件的最后一行时文件具有奇数行数,则 while 语句中对 null 的检查允许代码进入循环,但以下 ReadLine 返回 null 字符串。当然,尝试读取空字符串索引零处的字符会引发 NRE 异常。

文件中还存在空行的问题。如果有一个空行,则再次读取索引零将抛出索引超出范围异常

你可以用这种方式修复你的代码

public bool Load(string fileName)
{
    string appointmentData = string.Empty;
    using (StreamReader reader = new StreamReader(fileName))
    {
        while((appointmentData = reader.ReadLine()) != null)
        {
            if(!string.IsNullOrWhiteSpace(appointmentData))
            {
                if(appointmentData[0] == 'R')
                    this.Add(appointment = new RecurringAppointment(appointmentData));
                else
                    this.Add(appointment = new Appointment(appointmentData));
            }
        }
        return true;
    }
}