我一直在查看这段代码来创建一个基本的购物车,但缺点是它使用静态方法,因此购物车项目(当添加到购物车时)在会话之间共享。有人可以指出如何修改 ShoppingCart 方法以消除此限制吗?
但我确定这是有问题的代码
// Readonly properties can only be set in initialization or in a constructor
public static readonly ShoppingCart Instance;
// The static constructor is called as soon as the class is loaded into memory
static ShoppingCart() {
// If the cart is not in the session, create one and put it there
// Otherwise, get it from the session
if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) {
Instance = new ShoppingCart();
Instance.Items = new List<CartItem>();
HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
} else {
Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
}
}
// A protected constructor ensures that an object can't be created from outside
protected ShoppingCart() { }
public void AddItem(int productId) {
// Create a new item to add to the cart
CartItem newItem = new CartItem(productId);
// If this item already exists in our list of items, increase the quantity
// Otherwise, add the new item to the list
if (Items.Contains(newItem)) {
foreach (CartItem item in Items) {
if (item.Equals(newItem)) {
item.Quantity++;
return;
}
}
} else {
newItem.Quantity = 1;
Items.Add(newItem);
}
}