C# 从文本文件创建对象 - System.NullReferenceException

问题描述

我有一项任务要完成,但我无法弄清楚我做错了什么,是否根本没有创建对象的实例,或者是否没有对元素数组的引用。错误:System.NullReferenceException。 任务是从一个文本文件中启动 20 个对象,每一行代表一个对象的实例。程序应该读取创建每个对象的文件并更新指向新创建对象的指针数组。 到目前为止,代码运行文本文件并将字符串转换为适当的类型。看起来它也初始化了对象并将它们指向家畜 [] 数组。但是,当尝试运行任何与对象相关的方法时,出现空引用错误。要求是使用数组来创建新对象。 任何帮助将不胜感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {                     
            Livestock[] livestocks =  new Livestock[20]; //array of 20 pointers to Livestock.
                          
            
            String textLine;
            String[] livestockContent; //array of Livestock textfile content

            //The task of this progrgam is to read the file line by line
            try
            {
                TextReader textReader = new StreamReader(@"C:\...file.txt");
                while ((textLine = textReader.ReadLine()) != null)
                {
                    livestockContent = textLine.Split(','); //The line Could be splitted to words
                    int _ID = int.Parse(livestockContent[0]);
                    string _livestockType = livestockContent[1];
                    int _yearBorn = int.Parse(livestockContent[2]);
                    double _costPerMonth = double.Parse(livestockContent[3],CultureInfo.InvariantCulture);
                    double _costPerVaccination = double.Parse(livestockContent[4],CultureInfo.InvariantCulture);
                    double _amountOfMilk = double.Parse(livestockContent[5],CultureInfo.InvariantCulture);
                    

                    if (_livestockType != null )
                    {
                         for (int i = 0; i > 20; i++)

                            livestocks[i]  = new Livestock(_ID,_livestockType,_yearBorn,_costPerMonth,_costPerVaccination,_amountOfMilk);
                         
                      //Console.WriteLine("Creating a new: " + livestocks[0]);
                      //Console.WriteLine("Livestock ID is: " + ID);

                    }
                    else
                    {
                       for (int i = 0; i > 20; i++)
                            livestocks[i] = new Livestock(_ID,_amountOfMilk);

                        
                      livestocks[9].GetID();
                    }
                }//end of while //end of reading the file and initiating objects
            }//end of try
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
            }// end of catch
           Console.ReadKey();       
       }//end of main method 
    }// end of class
}//end of namespace

解决方法

在这里,您对 _livestockType 变量进行空检查,但如果它为空,则将其添加到对象中。

我会说您将 _livestockType 作为 null 传递给对象并尝试在方法中访问它,因此抛出 NullReferenceException

if (_livestockType != null )
{
     for (int i = 0; i > 20; i++)

        livestocks[i]  = new Livestock(_ID,_livestockType,_yearBorn,_costPerMonth,_costPerVaccination,_amountOfMilk);
     
  //Console.WriteLine("Creating a new: " + livestocks[0]);
  //Console.WriteLine("Livestock ID is: " + ID);

}
else
{
   for (int i = 0; i > 20; i++)
        livestocks[i] = new Livestock(_ID,_amountOfMilk);

    
  livestocks[9].GetID();
}