英文:
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<InventoryItem> items = new List<InventoryItem>();
<!-- 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() && 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];
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论