2010-02-25 94 views
1

我有以下类。在尝试使用以下代码设置员工类的值时,我收到错误消息:对象引用未设置为对象的实例。创建对象帮助数组

我该如何解决?

public class Employee 
{ 
    public Test[] test{ get; set; } 

     public Employee() 
     { 
      this.test[0].Name = "Tom"; 
      this.test[0].age= 13; 

     } 
} 



public class Test 
{ 
    public string Name {get; set;} 
    public int Age {get; set;} 
} 

回答

1

您需要创建测试变量的实例,它是对象的试验[]数组分配之前任何值给他们。创建实例时,您必须设置它将保存的元素数量。

public class Test 
    { 
     public string Name { get; set; } public int age { get; set; } 
    } 

    public class Employee 
    { 
     public Test[] test { get; set; } 

     public Employee() 
     { 
      test = new Test[1]; 
      this.test[0] = new Test(); 
      this.test[0].Name = "Tom"; 
      this.test[0].age = 13; 

     } 
    } 

如果你不知道测试的数量obejct数组将举行,考虑使用ListArrayList

编辑。列表示例:

public class Employee 
    { 
     public List<Test> test { get; set; } 

     public Employee() 
     { 
      this.test.Add(new Test()); 
      this.test[0].Name = "Tom"; 
      this.test[0].age = 13; 

     } 
    } 

    public class Test 
    { 
     public string Name { get; set; } public int age { get; set; } 
    } 
+0

我仍然收到“this.test.Add(new Test())”级别的错误消息;“ – learning 2010-02-25 12:34:57

+0

最新的错误信息?顺便说一句,在你最初的例子中,当你对它进行decalred时,你将Test类命名为“test”(小写字母t),但是当你在Employee类中使用它时,试图用Capital T(“Test”)来使用它。 确保行“public class Test {....}是正确的。我编辑了我的第二个代码,以便它包含正确的Test类 – 2010-02-25 15:10:25

1

试图用艾德里安

例如之前的数组元素,您应该创建阵列的一个实例,并

test = new Test[1]{new Test()}; 

test = new Test[1]; 
test[0] = new Test(); 

比你可以使用艾德里安

this.test[0].Name = "Tom"; 
this.test[0].age= 13; 

如果你想实际上包含构建阵列测试元素,那么您可以使用此代码:

Test[] arrT = new Test[N]; 
for (int i = 0; i < N; i++) 
{ 
    arrT[i] = new Test(); 
} 
+0

感谢您的回复。随着以下,我仍然有错误消息:对象引用未设置为对象的实例。 test = new Test [1] {new Test()}; this.test [0] .Name =“Tom”; this.test [0] .age = 13; – learning 2010-02-25 12:14:51

+0

我不这么认为,你在另一个地方做错了事。它的工作对我来说很完美 – 2010-02-25 12:18:27

+0

我已经尝试了两个答案,但无法找出为什么我会收到错误消息! – learning 2010-02-25 12:37:40