我一直在尋找這樣的代碼來創建一個基本的購物車,但缺點是,它使用一個靜態方法&因此(在添加到購物籃)購物車項目在會話之間共享。有人能指出如何修改ShoppingCart方法來消除這個限制嗎?C#購物車
但是我相信這是有問題的代碼
// 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);
}
}
如果您使用包含用戶特定數據的靜態變量,則所有用戶都將訪問該數據。 – Matthew 2012-04-20 17:08:40
@David - 購物籃內容使用DES加密,然後發佈給第三方支付提供商並由其處理,所以是的,我知道ecommcerce的安全/ PCI方面。至於購買第三方解決方案,對於這樣一個小項目來說,這不是一個真正的選擇。 – 2012-04-20 19:05:00
@Matthew,謝謝我也知道這一點:O) – 2012-04-20 19:05:31