C#If,Else-If奇数错误

本文关键字:错误 Else-If C#If | 更新日期: 2023-09-27 18:00:50

我正在为C#创建一个库存程序,到目前为止,我已经编写了一个函数来打印库存中的所有项目,现在我正在创建一个函数以获取有关项目的更多信息。当我打印出我的库存时,它只打印出我物品的名称。这个功能将打印所有细节,这样,如果它是一件武器,它就会打印出它的名称、伤害和暴击

这是我的GetInfo函数:

  public void GetInfo()
{
    Console.WriteLine("If you want more detail about an item, type the number to its left.  'nOtherwise, type (Q)");
    int getinfo;
    int.TryParse(Console.ReadLine(), out getinfo);
    getinfo -= 1; 
    if(getinfo > InventorySlots || getinfo < 0)
    {
        throw new System.Exception("You entered an invalid number"); 
    }
    if (weapons.Count >= getinfo)
    {
        Console.Clear(); 
        Console.Write("Weapon Name: " + weapons[getinfo].name + "'nDamage: " + weapons[getinfo].damage + "'nCritical: " + weapons[getinfo].critical);
        Console.ReadLine(); 
    }
    else if ((weapons.Count + armors.Count) >= getinfo)
    {
        Console.Clear();
        Console.Write("Armor Name: " + armors[getinfo].name + "'nArmor Value: " + armors[getinfo].armor + "'nHealth Boost: " + armors[getinfo].healthboost);
        Console.ReadLine(); 
    }
    else if ((weapons.Count + armors.Count + ores.Count) >= getinfo)
    {
        Console.Clear();
        Console.Write("Ore Name" + ores[getinfo].name + "(" + ores[getinfo].stack + ")"); 
    }
}

现在,问题是声明:

if(weapons.Count >= getinfo

正在执行,尽管getinfo比武器还大。计数如果语句无效,为什么要执行该语句?

谢谢。

C#If,Else-If奇数错误

现在,问题是声明。。。正在执行,尽管getinfo比武器还大。计数

大概你这么说是因为当代码到达以下位置时,你得到了一个IndexOutOfBoundsException

weapons[getinfo].name

所以你假设getinfo大于weapons.Count。但事实上,它等于weapons.Count。在C#中,对列表和数组的索引访问是从零开始的,这意味着weapons[weapons.Count - 1]是该集合中的最后一个项。

if语句更改为:

if (weapons.Count > getinfo)