Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中尝试调用ArrayList中索引的对象的方法#_C#_Object_Methods_Arraylist - Fatal编程技术网

C# 在C中尝试调用ArrayList中索引的对象的方法#

C# 在C中尝试调用ArrayList中索引的对象的方法#,c#,object,methods,arraylist,C#,Object,Methods,Arraylist,我是C语言的新手,我正在编写一个程序,其中我有一个单元对象的数组列表(unitArray),我试图对数组列表中引用的对象调用一个非静态方法。我尝试访问特定对象并调用它的方法,但它不起作用。我非常感谢你帮助我解决这个问题 Unit.unitArray[selectedUnit].DisplayUnitAttributes() 我得到以下例外情况: 'object' does not contain a definition for 'DisplayUnitAttributes' and no e

我是C语言的新手,我正在编写一个程序,其中我有一个
单元
对象的
数组列表
unitArray
),我试图对
数组列表
中引用的对象调用一个
非静态
方法。我尝试访问特定对象并调用它的方法,但它不起作用。我非常感谢你帮助我解决这个问题

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?) 

您需要将对象强制转换为其类型。代替下面的MyClass,替换实际的类类型

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

ArrayList
中提取的元素类型是
System.Object
,它是C#中所有对象的基类

您必须将元素强制转换为派生类型才能访问方法,或者最好使用
System.Generic.List
,其中T是列表中元素的类型。

您可以使用它来获取必要的子数组。大概是这样的:

foreach (YourClass obj in Unit.unitArray.OfType<YourClass>())
    obj.DisplayUnitAttributes();
foreach(Unit.unitArray.OfType()中的YourClass对象)
obj.DisplayUnitAttributes();

Word。我的人!非常感谢。这是ArrayList的特殊角色吗?我怀疑这是因为这些对象可能包含不同类型的对象?或者您可以将其转换为((MyClass)Unit.unitArray[selectedUnit]).DisplayUnitAttributes(),如果对象类型错误,则会引发无效的转换异常,而不是空对象引用引发的泛型异常。@user1676520:correct,arraylist存储对象。因此,当你检索时,你必须从一个对象中转换它。虽然你已经得到了不同的答案,但我想你应该关注cdiggins的答案,如果你的
ArrayList
中的所有元素都是同一类型的,因为在更常见的
ArrayList
中没有意义。我喜欢这个。以前从未使用过。@Valamas也爱上了它。使用此选项筛选“公共类型”集合非常有用。相反,我几乎从不使用Enumerable.Cast方法。