对象的数组属性的NullReferenceException

我有一个类实现如下:

class Person { public int ID { get; set; } public string FName { get; set; } public string LName { get; set; } public double[] Fees { get; set; } public Person() { } public Person( int iD, string fName, string lName, double[] fees) { ID = iD; FName = fName; LName = lName; Fees = fees; } } 

然后我试图在一个简单的按钮点击事件中测试代码,如下所示:

 Person p = new Person(); p.ID = 1; p.FName = "Bob"; p.LName = "Smith"; p.Fees[0] = 11; p.Fees[1] = 12; p.Fees[2] = 13; for (int i = 0; i < p.Fees.Length; i++) { lstResult.Items.Add(p.ID + ", " + p.FName + ", " + p.LName + ", " + p.Fees[i]); } 

我现在保持一切基本和简单,只是为了得到我需要的工作。

Visual Studio在运行程序时出现此错误:

NullReferenceException was unhandled

该错误与Person对象的Fees数组属性有关。 我需要将数组作为对象的属性,以便我可以将费用与特定人员相关联。 因此,除非我在这里尝试做的事情是不可能的,否则我希望在课堂上保持相同的设置。

  • 我没有正确实例化对象吗?
  • 我是否需要做更多的事情来初始化数组属性?
  • 谁能看到我遇到的问题?

我愿意接受有关使用字典或其他数据结构的想法。 但是,如果我在这里尝试做的事情绝对不可能。

我在谷歌上四处寻找并且没有运气。 我看过旧课堂笔记和示例项目,没有运气。 这是我最后的希望。 有人请帮忙。 在此先感谢大家。

您正在忽略数组初始化,正如其他人所指出的那样。

 p.Fees = new double[3]; 

但是,通用List更适合几乎所有使用数组的地方。 它仍然是相同的数据结构。

当您向其添加和删除项目时,List会自动缩小和扩展,从而无需自行管理arrays的大小。

考虑这个类(请注意,您需要导入System.Collections.Generic)

  using System.Collections.Generic; class Person { public int ID { get; set; } public string FName { get; set; } public string LName { get; set; } public List Fees { get; set; } public Person() { } public Person( int iD, string fName, string lName, List fees) { ID = iD; FName = fName; LName = lName; Fees = fees; } } 

现在,这是您的测试方法应该如何

  Person p = new Person(); p.ID = 1; p.FName = "Bob"; p.LName = "Smith"; p.Fees = new List(); p.Fees.Add(11); p.Fees.Add(12); p.Fees.Add(13); for (int i = 0; i < p.Fees.Count; i++) { lstResult.Items.Add(p.ID + ", " + p.FName + ", " + p.LName + ", " + p.Fees[i]); } 

您仍然需要创建Fees属性的新实例,但您现在不必担心初始化数组的大小。 对于奖励积分,如果需要使用ToArray(),可以轻松将其转换为数组

 p.Fees.ToArray(); 

在您正在调用的默认构造函数中,您不会初始化fees

 public Person() { this.Fees = new double[10]; // whatever size you want } 

这个

 Person p = new Person(); p.ID = 1; p.FName = "Bob"; p.LName = "Smith"; p.Fees[0] = 11; p.Fees[1] = 12; p.Fees[2] = 13; 

应该翻译成这个

 Person p = new Person(1,"Bob","Smith",new double[]{ 11, 12, 13 }); 

添加以下行

 p.Fees = new double[3]; 

之前

 p.Fees[0] = 11; 

你需要费用。 例如

 Person p = new Person(); p.ID = 1; p.FName = "Bob"; p.LName = "Smith"; p.Fees = new double[] {11, 12, 13};