2013-10-01 22 views
0

的数组属性我有,因为这实现了一个类:的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]); 
} 

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

NullReferenceException was unhandled

误差与Person对象的费用阵列物业办:当我运行该程序

Visual Studio中给出了这样的错误。我需要将数组作为对象的属性,以便我可以将费用与特定的人联系起来。所以除非我想在这里做什么是不可能的,我想在课堂上保持同样的设置。

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

我很乐意接受有关使用字典或其他数据结构的想法。但只有当我想在这里做什么是绝对不可能的。

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

+1

您需要分配的数组:'p.Fees =新的双[3];' –

回答

4

您错过了其他人指出的数组初始化。

p.Fees = new double[3]; 

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

当您添加和删除项目时,列表会自动缩小和扩大,无需自己管理阵列的大小。

考虑这个类(请注意,您需要导入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<double> Fees { get; set; } 

    public Person() 
    { } 

    public Person(
     int iD, 
     string fName, 
     string lName, 
     List<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 = new List<double>(); 
     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]); 
     } 

您仍然需要创建一个新的费用属性的实例,但您现在不必担心初始化数组的大小。对于加分,你可以很容易地通过使用ToArray的它改造成一个数组,如果你需要()

p.Fees.ToArray(); 
+0

谢谢!很好的答案! – Zolt

1

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

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

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 }); 
1

添加以下行

p.Fees = new double[3]; 

p.Fees[0] = 11; 
1

您需要支付费用。例如

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