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



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

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, _livestockType, _yearBorn, _costPerMonth, _costPerVaccination, _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变量为null,但如果为null,则将其添加到对象中。

我想说,您将_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, _livestockType, _yearBorn, _costPerMonth, _costPerVaccination, _amountOfMilk);

livestocks[9].GetID();
}

相关内容

最新更新