2010-02-25 95 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