如何迭代包含对象的列表?C#

0 c# foreach list object

我创建了一个列表来存储另一个类的对象。存储在我的列表中的每个对象都有一个名称和一个整数。我想知道是否可以迭代列表并显示每个对象的名称。如果我将 i 的类型更改为 VAR 或 Dynamic,它会说超出范围。

    public List<InventoryHandling> Inventory = new List<InventoryHandling>();

    public void inventorySelect()
    {
        Inventory[0] = new InventoryHandling("Potion", 4);

        foreach(int i in Inventory)
        {
            Console.WriteLine(Inventory[i].Name);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Joe*_*orn 6

首先,这一行是错误的:

Inventory[0] = new InventoryHandling("Potion", 4);
Run Code Online (Sandbox Code Playgroud)

问题是[0]索引引用列表中的第一项,但(大概)此时列表还没有任何空间。索引处的位置[0] 不存在,并且 C# 不允许您通过分配下一个索引来追加到列表。相反,当您想将新项目添加到列表中时,您应该调用它的.Add()方法:

Inventory.Add(new InventoryHandling("Potion", 4));
Run Code Online (Sandbox Code Playgroud)

现在我们有了一个包含一些内容的列表,我们可以讨论如何迭代它。就像附加一样,您不使用foreach循环的索引:

foreach(InventoryHandling ih in Inventory)
{
    Console.WriteLine(ih.Name);
}
Run Code Online (Sandbox Code Playgroud)

如果你确实想使用索引,你可以用循环来完成for

for(int i = 0; i < Inventory.Length; i++)
{
    Console.WriteLine(Inventory[i].Name);
}
Run Code Online (Sandbox Code Playgroud)