以下课程是我为购物篮创建的。我是否朝着实现预期结果的方向前进?
namespace Basket
{
public class ShoppingBasket
{
private string productName;
private decimal latestProductValue;
private int quantity;
private decimal Total;
public void AddProduct( string productName, decimal latestProductValue, int quantity)
{
string ProductName = productName;
decimal LatestProductValue = latestProductValue;
int Quantity = quantity;
}
public string ProductName
{
get { return productName; }
set
{
if (productName == ProductName)
productName = ProductName;
}
}
public decimal LatestProductValue
{
get { return latestProductValue; }
set
{
if (latestProductValue == LatestProductValue)
latestProductValue = LatestProductValue;
}
}
public int Quantity
{
get { return quantity; }
set
{
if (quantity > 0)
quantity = value;
}
}
public decimal GetTotal
{
get { return quantity * latestProductValue; }
}
}
}
答案 0 :(得分:0)
示例项目:https://dl.dropboxusercontent.com/u/70244715/BasketTest.rar
这是你应该怎么做的:
BasketItem类
public class BasketItem {
private string itemName = string.Empty;
private decimal itemPrice = 0;
public string ItemName {
get {
return itemName;
}
set {
itemName = value;
}
}
public decimal ItemPrice {
get {
return itemPrice;
}
set {
itemPrice = value;
}
}
}
购物篮类
public class Basket {
private List<BasketItem> lstBasketItems = new List<BasketItem>();
public void AddItemToBasket(BasketItem addedItem) {
lstBasketItems.Add(addedItem);
}
public decimal CalculateTotal() {
decimal total = lstBasketItems.Sum(x => Convert.ToDecimal(x.ItemPrice));
return total;
}
}
在表单中使用它们:
BasketItem insItem = new BasketItem();
Basket insBasket = new Basket();
insItem.ItemName = "My Item 1";
insItem.ItemPrice = 10;
insBasket.AddItemToBasket(insItem);
Console.WriteLine(insBasket.CalculateTotal());
这是一个非常简单的例子,没有经过测试。我试着告诉你应该如何实现它。也不是说这个例子不处理在页面调用之间存储篮子。您很可能使用会话状态或类似的东西来实现逻辑。