Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        2年前关闭。
                                                                                            
                
        
我一直在看这段代码来创建基本的购物车,但是缺点是它使用静态方法,因此购物车中的物品(添加到购物篮中时)在各个会话之间共享。有人可以指出如何修改ShoppingCart方法以消除此限制吗?

Full Code reference is here

但我确定这是令人讨厌的代码

// 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);
    }
}

最佳答案

如果您使用静态变量,那么任何线程(无论哪个用户)都可以访问该数据。这意味着您基本上可以在所有用户之间共享一张购物卡,我怀疑您不想这样做。

相反,可以有一个受保护的构造函数来防止手动实例化,然后有一个静态方法来读取Session对象并获取当前实例。至于填写Items列表的静态方法,您应该在构造函数中执行。

public static ShoppingCart GetInstance()
{
    ShoppingCart cart = (ShoppingCart)Session["ASPNETShoppingCart"];

    if (cart == null)
    {
        Session["ASPNETShoppingCart"] = cart = new ShoppingCart();
    }

    return cart;
}

protected ShoppingCart()
{
    Items = new List<CartItem>();
}

关于c# - C#购物车,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10250288/

10-17 01:07