我正在try 在列表中查找项目的索引,其中包含类似内容
listx.FindIndex(SomePredicate<T>)
但我得到了一个错误
NullReferenceResponse:对象引用未设置为对象的实例
起初我不太确定它是什么,所以我也try 使用类似listx.Exists(SomePredicate<T>)
的东西.该列表具有固定长度并且确实包含空值(用于在Unity中构建库存系统).
我的(非常)简化代码:
public class Item
{
public int id;
public string itemname;
// constructor etc ...
}
// in another class:
List<Item> inventory = new List<Item>();
for (int i = 0; i < 4; i++)
{
inventory.Add(null);
}
inventory[0] = new Item(0, "YellowBox");
inventory[1] = new Item(1, "RedBox");
// inventory[2] stays null
// inventory[3] stays null
string itemname = "RedBox";
inventory.Exists(item => item.itemname == itemname)
// WORKING because it finds a match before it runs into a null
string itemname = "BlueBox";
inventory.Exists(item => item.itemname == itemname)
// NOT WORKING, I guess because it runs into a null in inventory[2]
// and it can't get an itemname from null
有人知道首先判断空或有.Exists
的替代方案吗?
写这个问题我现在有了一个 idea .我认为仅仅跳过空是不够的,因为我需要索引,但可能是这样的.
public int FindItemIndex(string itemname)
{
int index;
for (int i = 0; i < 4; i++)
{
if (inventory[i] == null)
{
index = -1;
continue;
}
if (inventory[i].itemname == itemname)
{
return i;
}
index = -1;
}
return index;
}
然后我可以使用类似的内容:
if (FindItemIndex(string itemname) < 0)
{
// code for item not found
}
else
{
// code where I use the index, for example remove item at inventory[index]
}
或者inventory.Where(Item => Item != null)
可以使用吗?
我很感激一些建议