1

我正在为 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 大于武器数量,也正在执行。如果语句无效,为什么会执行该语句?

谢谢。

4

1 回答 1

1

现在,问题是语句 ... 正在执行,即使 getinfo 大于武器数量。

大概你这么说是因为IndexOutOfBoundsException当代码遇到这个时你会得到一个:

weapons[getinfo].name

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

if将您的声明更改为:

if (weapons.Count > getinfo)
于 2013-02-23T19:07:22.970 回答