【问题标题】:Selecting objects contained in an ArrayList选择 ArrayList 中包含的对象
【发布时间】:2010-12-18 19:30:03
【问题描述】:

我正在做一个家庭作业项目,我有一个包含 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.

【问题讨论】:

  • “IndexOf”或“Contains”方法不是您需要在这里使用的吗?

标签: c# object arraylist


【解决方案1】:

ArrayList 不知道(或关心)其中放置了哪种对象。它将放入其中的所有内容都视为对象。从 ArrayList 检索对象时,您需要将返回的 Object 引用转换为适当类型的引用,然后才能访问该类型的属性和方法。有几种方法可以做到这一点:

// 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 代码难以编写且容易出错的强制转换。缺点当然是您不能在列表中混合类型。 List 不会让您在其中放入字符串,而充满 Equipment 实例的 ArrayList 则可以。您尝试解决的特定问题将决定哪个更有意义。

【讨论】:

    【解决方案2】:

    使用 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
    }
    

    如果这能解决您的问题,请告诉我。

    【讨论】:

      【解决方案3】:

      由于数组列表中的所有项目表面上都是“对象”,但实际上它们实际上是设备对象,因此在从 ArrayList 检索项目时,您需要一种从对象到设备的方法(提示:演员)。不想放弃,因为这是家庭作业,但这应该会有所帮助....

      【讨论】:

      • 因为这是 c#,所以不要使用 (object) cast 类型。您应该使用另一个关键字。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 2015-05-02
      • 2020-04-13
      • 2012-11-14
      • 2014-12-11
      • 1970-01-01
      相关资源
      最近更新 更多