【发布时间】:2021-08-14 19:37:28
【问题描述】:
所以我写了一个基本库存系统的代码,我的代码在更新时有一个基本错误,列表中的完整项目正在更新,而不是作为参数传递的首选 id,以及删除函数显示“集合已修改;枚举操作可能无法执行”的错误。 我还是个初学者
//This is my update method
public void Update(int prodID)
{
if (prodID <= ProductList.Count)
{
foreach (Product p in ProductList)
{
if (ProductList.Exists(p => p.ProductId == prodID))
{
Console.WriteLine("Product Name:");
string Name = Console.ReadLine();
Console.WriteLine("Product No.:");
string Productno = Console.ReadLine();
Console.WriteLine("Price:");
decimal Price = int.Parse(Console.ReadLine());
p.ProductName = Name;
p.ProductNo = Productno;
p.ListPrice = Price;
}
}
}
else
{
Console.WriteLine("ENTER A VALID PRODUCT ID\n");
}
}
//This is my Delete method
public void Delete(int prodID)
{
if (prodID <= ProductList.Count)
{
foreach (Product p in ProductList)
{
if (ProductList.Exists(p => p.ProductId == prodID))
{
ProductList.RemoveAt(prodID - 1);
Console.WriteLine("THE PRODUCT IS SUCCESSFULLY DELETED.\n");
}
}
}
else
{
Console.WriteLine("ENTER A VALID PRODUCT ID\n");
}
}
【问题讨论】:
-
您正在检查列表中是否存在 ProductId,而不是检查当前产品是否具有所需的产品 ID。如果产品曾经在列表中,它将永远存在 - 因此所有项目都将被更新。