2013-04-30 47 views
0

我有一個類和一個數組。該數組被聲明爲類型:Class。如何爲一個類數組的一個屬性賦值?

//Class 
public class TestClass 
{ 
    public int testint { get; set; } 
     public string teststr { get; set; } 
    public TestClass(int _testint, string _teststr) 
    { 
     testint = _testint; 
      teststr = _teststr; 
    } 
} 

//Array declaration 
TestClass[] MyArray = new TestClass[ 3 ]; 

現在我想做的事情(這是僅用於測試 - 我心中有一個更大的代碼使用這種方法我想工作的時候):

我想能夠只設置teststr或僅僅是陣列單元的testint,如下所示:

MyArray[ 0 ].testint = 3; 

這不會返回任何錯誤,但是如果我嘗試打印這個;結果爲空(空 - 空)。

我使用Blend 4與Silverlight - 請幫助,如果你知道如何分配單一的屬性,像我想在這裏!

+4

我很驚訝,你沒有一個空指針異常...... 嘗試做' MyArray [0] = new TestClass(){testint = 3}'代替。 – Thomas 2013-04-30 12:57:25

+1

我希望您想到的更大的代碼具有大寫的屬性名稱。 – 2013-04-30 12:59:57

+1

@Thomas:我想這是因爲這段代碼參與了一些綁定機制(請參閱Blend 4 with Silverlight),所以NullPointerException應該由UI處理。 – 2013-04-30 13:02:54

回答

3

您必須創建一個TestClass的實例,因爲您剛剛創建了一個空數組,即該數組有3個引用爲空。

TestClass[] MyArray = new TestClass[ 3 ]; 

MYARRAY是{null, null, null},所以MyArray[0] == null

MyArray[0] = new TestClass(42, "42"); 

MYARRAY是{anObject, null, null}

MyArray[0].testint = 3; // this is valid 
+0

upvote,因爲我看不出爲什麼有一個downvote ... – 2013-04-30 13:01:05

+0

當我嘗試這個,我得到這條線上的錯誤CS1729: 'MyArray [0] = new TestClass();' – 2013-04-30 13:07:04

+0

您沒有en空構造函數,所以你不能無參數地調用TestClass()。您可以爲您的TestClass()添加一個空的構造函數,或者爲構造函數提供參數以匹配您現有構造函數的簽名。 – 2013-04-30 13:09:39

相關問題