【发布时间】:2021-06-26 23:28:58
【问题描述】:
我有一个任务要完成,但我不知道我做错了什么以及对象的实例是否根本没有创建,或者是否没有对元素数组的引用。错误: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, _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
【问题讨论】:
-
将
i > 20更改为i < 20为for loops。或者更好的是,i < livestocks.Length -
我非常怀疑您使用的是 C# 2。