ArgumentOutOfRangeException for if statement

huangapple go评论61阅读模式
英文:

ArgumentOutOfRangeExeption for if statement

问题

这是引发错误的代码片段:

if (items[0] != null)
{
    equippedItem = items[0];
}

这是项目列表的一部分:

public List<InventoryItem> items = new List<InventoryItem>();

这是已装备物品的一部分:

public InventoryItem equippedItem;
英文:

Here is a snippet of the code that is causing the error

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-c# -->

if(items[0] != null)
{
    equippedItem = items[0];
}

<!-- end snippet -->

Here is a snippet of the items list:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-c# -->

public List&lt;InventoryItem&gt; items = new List&lt;InventoryItem&gt;();

<!-- end snippet -->

Here is a snippet of the
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-c# -->

public InventoryItem equippedItem;

<!-- end snippet -->

答案1

得分: 1

我会更改这部分代码:

if(items[0] != null)
{
    equippedItem = items[0];
}

改为:

if(items.Any() && items[0] != null)
{
    equippedItem = items[0];
}

这将检查列表是否已初始化并包含项目。如果有项目,你可以从列表中获取第一个项目。

如果你真的希望始终从列表中获取第一个项目,也许可以使用这样的方式:

InventoryItem equippedItem = items.FirstOrDefault();

if(equippedItem != null)
{
    // 添加一些精彩的代码
}

FirstOrDefault 会从列表中获取第一个项目。如果没有第一个项目,结果将是类型的默认值(int = 0,bool = false,InventoryItem = null)。你也可以使用 First(),但如果没有第一个(索引0),它将引发异常。

我会尽量避免使用索引,因为它对错误非常敏感。

英文:

I would change this:

if(items[0] != null)
{
    equippedItem = items[0];
}

To this:

if(items.Any() &amp;&amp; items[0] != null)
{
    equippedItem = items[0];
}

This will check if the list is initialized and has items. If it does have items, you can get the first item from the list.

And if you really want to get the first item from that list at all times, maybe use something like this:

InventoryItem equippedItem = items.FirstOrDefault();

if(equippedItem != null)
{
    // Add some cool code    
}

The FirstOrDefault gets the first item from a list. If there isn't a first item, the result will be the default value of the type (int = 0, bool = false, InventoryItem = null). You could also use First(), but that would throw an exception if there isn't a first (index 0).

I would try to avoid indexes as much as possible, because it's very sensitive for errors.

答案2

得分: 0

if (items.Count != 0)
{
if(items[0] != null)
{
equippedItem = items[0];
}
}

英文:

I actually found specifically that if you do this it works:

if (items.Count != 0)
        {
            if(items[0] != null)
            {
                equippedItem = items[0];
            }
        }

huangapple
  • 本文由 发表于 2023年2月10日 15:58:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定