2017-07-27 208 views
0

我想做一個整數值的數組列表,並運行一些基本的數學運算,如下所示。在c#unity中定義數組列表。

int dice1 = 4; 
int dice2 = 3; 
int dice3 = 6; 
int dice4 = 4; 
int dice 5 = 5; 

ArrayList numbers = new ArrayList(); 
     numbers[4] = dice5; 
     numbers[3] = dice4; 
     numbers[2] = dice3; 
     numbers[1] = dice2; 
     numbers[0] = dice1; 

numbers[3] = numbers[3] * numbers[2]; 

但是,計算機不允許我這樣做,會產生一個錯誤「操作‘*’不能適用於類型‘對象’和‘對象’的操作數」。我該如何解決?我認爲我必須將數組列表定義爲一個整數數組......但是我不太確定。請保持簡單的答案,因爲我對C#團隊相當陌生。

謝謝!使用數組列表

使用List<int>int[]

然後所含的對象

回答

2

ArrayList中存儲的一切作爲一個「對象」,基本上是最基本類型的東西可以在C#中。你有幾個選擇。如果你想使用的ArrayList保持,那麼你就需要做投你相乘,喜歡的東西:

numbers[3] = ((int)numbers[3]) * ((int)numbers[2]) 

或者,你可以溝ArrayList和使用更現代的名單<>類型。您需要添加using System.Collections.Generic頂端,那麼你的代碼會像:

int dice1 = 4; 
int dice2 = 3; 
int dice3 = 6; 
int dice4 = 4; 
int dice5 = 5; 

List<int> numbers = new List<int>(); //List contains ints only 
    numbers[4] = dice5; 
    numbers[3] = dice4; 
    numbers[2] = dice3; 
    numbers[1] = dice2; 
    numbers[0] = dice1; 

numbers[3] = numbers[3] * numbers[2]; //Works as expected 

最後,如果你知道你的收藏只會有一定數量的事情,你可以使用數組來代替。您的代碼現在是:

int dice1 = 4; 
int dice2 = 3; 
int dice3 = 6; 
int dice4 = 4; 
int dice5 = 5; 

int[] numbers = new int[5]; //Creates an int array with 5 elements 
//Meaning you can only access numbers[0] to numbers[4] inclusive 
    numbers[4] = dice5; 
    numbers[3] = dice4; 
    numbers[2] = dice3; 
    numbers[1] = dice2; 
    numbers[0] = dice1; 

numbers[3] = numbers[3] * numbers[2]; //Works as expected 
+0

非常感謝您的回答。非常詳細,非常有幫助!我使用ArrayLists的原因是我可以從中刪除元素。 –

+0

在這種情況下,您也可以從List <>中刪除東西。這裏有一堆關於它的方法! https://msdn.microsoft.com/en-us/library/s6hkc2c4(v=vs.110).aspx –

1

避免被鍵入的而不是對象