2012-09-17 30 views
2

我是新的C#中的ArrayList索引對象的方法,我正在寫一個程序,我有一個ArrayListunitArrayUnit對象,我試圖呼籲一個non-static方法在ArrayList中引用的對象。我嘗試訪問特定對象並調用它的方法,但它不起作用。我會很感謝幫助解決這個問題。試圖調用C#

Unit.unitArray[selectedUnit].DisplayUnitAttributes() 

我得到以下異常:

'object' does not contain a definition for 'DisplayUnitAttributes' and no extension method 'DisplayUnitAttributes' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) 
+0

雖然你有不同的答案了,我想你應該關注的cdiggins THA回答,如果你的'ArrayList'的所有元素都是同一類型的,因爲沒有然後在更常見的'ArrayList'中感知。 – horgh

回答

5

您需要轉換對象作爲其類型。代替下面的MyClass,代替實際的類型中。

(Unit.unitArray[selectedUnit] as MyClass).DisplayUnitAttributes() 
+0

單詞。我的男人!謝謝一堆。這種投射與ArrayLists有什麼特別之處?我懷疑這是因爲這些可能包含不同類型的對象? – user1676520

+0

或者您可以將它轉換爲((MyClass)Unit.unitArray [selectedUnit])。DisplayUnitAttributes(),如果對象是錯誤的類型,將拋出無效的轉換異常,而不是空對象引用拋出的一般異常。 –

+0

@ user1676520:正確,arraylist存儲對象。所以當你檢索你不得不從一個對象投下它。 –

3

類型從ArrayList提取的元素的是System.Object這是基類在C#中的所有對象的。

您必須將元素轉換爲派生類型才能訪問方法或更好地使用System.Generic.List<T>,其中T是列表中元素的類型。

1

您可以使用Enumerable.OfType Method來獲得必要的子陣列。事情是這樣的:

foreach (YourClass obj in Unit.unitArray.OfType<YourClass>()) 
    obj.DisplayUnitAttributes(); 
+0

我喜歡這個。以前從未使用過。 –

+0

@Valamas也愛上它。用這個過濾「common-typed」集合非常有用。相反,我幾乎從不使用Enumerable.Cast 方法。 – horgh