【问题标题】:C# Creating Objects from a text file - System.NullReferenceException [duplicate]C# 从文本文件创建对象 - System.NullReferenceException [重复]
【发布时间】: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 < 20for loops。或者更好的是,i < livestocks.Length
  • 我非常怀疑您使用的是 C# 2。

标签: c# c#-2.0


【解决方案1】:

这里你检查_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, _livestockType, _yearBorn, _costPerMonth, _costPerVaccination, _amountOfMilk);

    
  livestocks[9].GetID();
}

【讨论】:

  • 我已遵循您的两个建议 CaveCoder 并将条件更改为 _livestockType = "Cow"。 Hayden 将运算符更改为
猜你喜欢
  • 2023-04-02
  • 2020-04-16
  • 2017-05-12
  • 2018-04-11
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多