我有一个问题,当我尝试以下列方式从任何列表中删除项目时,我无法做到这一点...为什么这样的错误是“使用未分配的局部变量”它的分配位置如下所示:
public void RemoveFrmList(int ProdId)
{
int _index;
foreach (Products item in BoughtItems)
{
if (item.ProductID == ProdId)
{
_index = BoughtItems.IndexOf(item);
}
}
BoughtItems.RemoveAt(_index);
}
可以采取哪些措施来消除此错误?
答案 0 :(得分:2)
if语句中的代码不一定会发生。将_index初始化为-1或某些“未找到”表示值,错误应该消失。
答案 1 :(得分:2)
什么是BoughtItems
?如果是List<T>
,只需使用RemoveAll
public void RemoveFrmList(int ProdId)
{
BoughtItems.RemoveAll( item => item.ProductID == ProdId );
}
略有偏离,但为什么RemoveFrmL会错过o?它只会伤害可读性。使用完整的单词。
答案 2 :(得分:1)
_index
是未分配的。但如果BoughtItems
没有Product
项,则您将拥有一个未分配的变量_index
。或许你永远不会得到item.ProductID == ProdID
的项目。
换句话说:
int _index;
foreach (Products item in BoughtItems)
{
//Code here is not executed during runtime for reasons stated above.
}
BoughtItems.RemoveAt(_index); //error here because _index was not assigned!
要解决此问题,您可以执行类似
的操作int _index = -1;
foreach (...)
{
//...
}
if (_index != -1){
BoughtItems.RemoveAt(_index);
}
else
{
//handle case if needed
}