You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何遍历存储对象的列表并显示对象名称?

问题解决:C# List遍历索引越界错误

错误原因分析

  1. List初始化错误:直接通过Inventory[0] = ...赋值是错误的——刚创建的List<InventoryHandling>是空集合,不存在索引0的元素,这会直接触发索引越界异常。
  2. foreach循环用法错误:foreach(int i in Inventory)逻辑完全错误,你的List存储的是InventoryHandling对象,并非int类型。改成var后,i实际是InventoryHandling实例,此时用Inventory[i]相当于把对象当作索引值使用,必然导致索引越界。

修正后的代码

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

public void inventorySelect()
{
    // 用Add方法向List添加元素,而非直接赋值索引
    Inventory.Add(new InventoryHandling("Potion", 4));
    // 直接遍历List中的每个InventoryHandling对象
    foreach (var item in Inventory)
    {
        Console.WriteLine(item.Name);
    }
}

额外说明

如果需要获取索引值,可改用for循环遍历:

for (int i = 0; i < Inventory.Count; i++)
{
    Console.WriteLine(Inventory[i].Name);
}

内容的提问来源于stack exchange,提问作者Ehab Nasir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 08:54:55