2011-02-19 30 views
1

如何使用索引器如果我們使用的是數組對象?你如何使用索引器與對象數組?

對於單個對象:

static void Main(string[] args) 
{ 
    MYInd mi = new MYInd(); 
    mi[1] = 10; 
    Console.WriteLine(mi[1]); 
    mi[2, 10] = 100; 
    Console.WriteLine(mi[2]); 

    Console.WriteLine(mi[3, 10]); 

我應該爲對象的數組做什麼?

MYInd[] mir = new MYInd[3]; 

我們如何使用每個對象和索引器?

回答

2

你有幾個選項,如果你想重複你做

foreach(MYInd mi in mir) 
    Console.WriteLine(mi[3, 10]); 

如果你想挑選出從陣列中的特定MYInd你可以做到這一步

Console.WriteLine(mir[1][3, 10]); // [1] picks out one object from the array 

或在兩個步驟中

MYInd mi = mir[1]; // pick out one object from the array 
Console.WriteLine(mi[3, 10]); 
+0

感謝您的答覆。但我試過這個,它給了我一個例外。例外:對象引用未設置爲對象的實例 – 2011-02-19 07:14:59

+0

@Thomas,它可能是您初始化數組(使用您在問題中編寫的`new`關鍵字),而不是對象本身。在創建數組後,嘗試使用for(int i = 0; i mpontillo 2011-02-19 07:19:02

0
mir[0][1, 2] 

但是你可以把它想象成:

(mir[0])[1, 2] 

方括號不是必需的,因爲[操作員從左到右進行分析(如(1 + 2)+ 3 = = 1 + 2 + 3,我想它被稱爲左結合,但我不知道肯定:-))

請記住,你來初始化數組和元素:

var mir = new MyInd[5]; 
for (int i = 0; i < mir.Length; i++) 
{ 
    mir[i] = new MyInd(); 
}