【问题标题】:Trying to call method of object indexed in ArrayList in C#尝试在 C# 中调用 ArrayList 中索引的对象的方法
【发布时间】:2012-09-09 06:32:52
【问题描述】:

我是 C# 的新手,我正在编写一个程序,其中我有一个 Unit 对象的 ArrayList (unitArray) 并试图调用 non-static 方法在ArrayList 中引用的对象上。我尝试访问特定对象并调用它的方法,但它不起作用。我将不胜感激帮助解决此问题。

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

【问题讨论】:

  • 虽然你已经得到了不同的答案,但我想你应该关注 cdiggins 的答案,如果你的 ArrayList 的所有元素都是同一种类型,因为在然后是更常见的ArrayList

标签: c# object methods arraylist


【解决方案1】:

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

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

【讨论】:

  • 字。我的男人!谢谢一堆。这对 ArrayLists 来说有什么特别的吗?我怀疑这是因为这些可能包含不同类型的对象?
  • 或者您可以将其转换为 ((MyClass)Unit.unitArray[selectedUnit]).DisplayUnitAttributes(),如果对象是错误类型,则会抛出无效转换异常,而不是通用异常由空对象引用抛出。
  • @user1676520:正确,arraylist 存储对象。因此,当您检索时,您必须从对象中转换它。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您可以使用Enumerable.OfType Method 来获取必要的子数组。像这样的:

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

    【讨论】:

    • 我喜欢这个。以前没用过。
    • @Valamas 也喜欢它。用它过滤“通用类型”集合非常有用。相反,我几乎从不使用 Enumerable.Cast 方法。
    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2019-01-10
    • 1970-01-01
    相关资源
    最近更新 更多