您好我正在尝试为一些课程制作购物篮计划我已经获得了一个不同类型的“购物篮”,但我不能让我的列表继续更新。所以我遇到的问题是'ShoppingBasketList()'需要一个返回类型,但在我得到的例子中它没有。我花了很多年时间试图弄清楚为什么,我只是不能。如果有人有任何想法将是一个很大的帮助!
public class ShoppingBasket
{
public List<ShoppingBasketItem> Items { get; private set; }
public ShoppingBasketList()
{
Items = new List<ShoppingBasketItem>();
}
internal static void AddToList(string productName, int quantity, decimal latestPrice)
{
for (int i = 0; i < Items.Count; i++)
{
// if the item is already in the list
if (Items[i].ItemName == productName)
{
Items[i].UpdateShoppingBasketList(quantity, latestPrice);
return;
}
}
// It's not in the list
ShoppingBasketItem sbi = new ShoppingBasketItem(productName, quantity, latestPrice);
Items.Add(sbi);
}
}
答案 0 :(得分:2)
public ShoppingBasketList()
{
Items = new List<ShoppingBasketItem>();
}
是构造函数声明(因为它没有指定返回类型)。构造函数应始终与其所属的类具有相同的名称。当您的类名为ShoppingBasketList
时,您的构造函数称为ShoppingBasket
。您应该将您的班级重命名为ShoppingBasketList
或将您的构造函数重命名为ShoppingBasket
。
例如
public ShoppingBasket()
{
Items = new List<ShoppingBasketItem>();
}
您可以阅读有关构造函数here的更多信息。
答案 1 :(得分:0)
您的程序通知您返回类型,因为您指定了return;
。因此,请移除return
中的for
。
for (int i = 0; i < Items.Count; i++)
{
// if the item is already in the list
if (Items[i].ItemName == productName)
{
Items[i].UpdateShoppingBasketList(quantity, latestPrice);
return; //replace me with something else...
}
}
相反,请添加looping invariant notFound
(或break
)。
Boolean notFound = true;
for (int i = 0; i < Items.Count && notFound; i++)
{
// if the item is already in the list
if (Items[i].ItemName == productName)
{
Items[i].UpdateShoppingBasketList(quantity, latestPrice);
notFound = false; //exiting the the loop
}
}
哦,您的方法ShoppingBasketList
被写为构造函数(public <Insert Name Here>
是构造函数),在声明类ShoppingBasket sb = new ShoppingBasket();
时会调用它。
public ShoppingBasketList()
{
Items = new List<ShoppingBasketItem>();
}
将其重命名为您的班级名称public ShoppingBasket
或将其完全删除,并在Items
中初始化您的declaration
。
答案 2 :(得分:0)
除了上述那些正确声明你应该将ShoppingBasketList()重命名为ShoppingBasket()的人之外,你不需要一个带有返回值的方法来查看你的项目。您已经声明了Items作为List。从您的ShoppingBasket()对象,您将通过myShoppingBasket.Items
获取您的列表