2009-11-20 51 views
0

我正在做一個家庭作業的項目,我有一個ArrayList包含5個字符串。我知道如何選擇ArrayList的項目(使用索引值),但不知道如何訪問對象字符串。任何幫助都會很棒。這是我一直試圖做的:選擇一個ArrayList中包含的對象

private ArrayList myComponents; 

private int listIndex = 0; 

myComponents = new ArrayList(); //Arraylist to hold catalog data 

equipment = new Equipment(itemName, itemType, itemDetails, itemMaintenance, itemId); 

myComponents.Add(equipment); 

// class file is called Equipment.cs 

// I know normally that equipment without the arraylist this would work: 
// equipment.getitemName(); 
// but combining with the arraylist is being problematic. 
+0

「IndexOf」或「Contains」方法不是您需要在這裏使用的方法嗎? – 2009-11-20 17:42:45

回答

0

由於在數組列表中的所有項目都在它的面前「對象」,但它們實際上是在幕後設備對象,你需要一種方法當從ArrayList中檢索項目時,從對象轉到設備(提示:Cast)。不想放棄它,因爲這是作業,但這應該有所幫助....

+0

因爲這是c#,所以不要使用(對象)強制類型。還有另外一個你應該使用的關鍵字。 – Woot4Moo 2009-11-20 17:01:34

1

你可能會更好使用List而不是ArrayList。一個ArrayList不是強類型這意味着你不能將數組內的東西/對象看作是「設備」,而只是像它們是一個通用的無聊對象。

List<Equipment> myComponents = new List<Equipment>(); 

equipment = new Equipment(itemName, itemType, itemDetails, itemMaintenance, itemId); 

myComponents.Add(equipment); 

foreach(Equipment eq in myComponents) 
{ 
    eq.getItemName(); 
    // do stuff here 
} 

讓我知道這是否解決了您的問題。

1

ArrayList不知道(或關心)在其中放置了什麼類型的對象。它將所有放入它的東西視爲一個對象。從ArrayList中檢索對象時,您需要將返回的對象引用轉換爲適當類型的引用,然後才能訪問該類型屬性和方法。有幾種方法可以做到這一點:

// this will throw an exception if myComponents[0] is not an instance of Equipement 
Equipment eq = (Equipment) myComponents[0]; 

// this is a test you can to to check the type 
if(myComponents[i] is Equipment){ 
    // unlike the cast above, this will not throw and exception, it will set eq to 
    // null if myComponents[0] is not an instance of Equipement 
    Equipment eq = myComponents[0] as Equipment; 
} 

// foreach will do the cast for you like the first example, but since it is a cast 
// it will throw an exception if the type is wrong. 
foreach(Equipment eq in myComponents){ 
    ... 
} 

這就是說,如果可能,你真的想使用泛型類型。最像ArrayList那樣工作的是List。泛型在很多情況下都有所幫助,以避免所有使ArrayList代碼易於編寫且容易出錯的轉換。不利的一面是,你不能混合列表中的類型。一個列表不會讓你放入一個字符串,而一個完整的設備實例的ArrayList將會。你試圖解決的特定問題將決定哪個更有意義。

相關問題