更多细节在这个底部。我的代码:
表格类:
public partial class Form1 : Form
{
public ShoppingBasket myBasket = new ShoppingBasket();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (myBasket.IsProductInBasket("Apples"))
{
MessageBox.Show("Yes");
}
else
{
MessageBox.Show("No");
}
}
}
订单项类:
public class OrderItem
{
public string ProductName { get; set; }
public decimal LatestPrice { get; set; }
public int Quantity { get; set; }
public decimal TotalOrder { get; set; }
public OrderItem(string productName, decimal latestPrice, int quantity)
{
ProductName = productName;
LatestPrice = latestPrice;
Quantity = quantity;
TotalOrder = latestPrice * quantity;
}
}
购物类:
public class ShoppingBasket : List<OrderItem>
{
public ShoppingBasket()
{
}
public Form1 fm1;
public bool IsProductInBasket(string productName) //Error of " 'ShoppingBasket.IsProductInBasket(string)': not all code paths return a value"
{
if (fm1.lstCart.Items.Count > 0)
{
for (int i = 0; i < fm1.lstCart.Items.Count; i++) // Warning of 'Unreachable code detected'
{
if (fm1.lstCart.Items[i].ToString().Contains(productName))
{
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
}
为什么我会收到这个错误?IsProductInBasket 将始终返回 true 或 false,列表框中永远不会有负数的值,因此如果计数为 0,则返回 false,如果计数为 0,则通过列表框,如果找到则返回 true,否则返回 false如果没有。