0

我正在使用下面的代码来维护购物车。会话中有一个错误,当我打开我的网站而不是浏览器时,当我从一个浏览器中选择项目然后到另一个浏览器时,会出现会话冲突,所以以前创建的会话已更新,尽管每个浏览器都必须有新的会话请有人帮助我了解会话中错误的区域。

#region Singleton Implementation

    // 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["ShoppingCart"] == null)
        {
            Instance = new ShoppingCart();
            Instance.Items = new List<CartItem>();
            HttpContext.Current.Session.Add("ShoppingCart", Instance);
        }
        else
        {
            Instance = (ShoppingCart)HttpContext.Current.Session["ShoppingCart"];
        }
    }

    // A protected constructor ensures that an object can't be created from outside
    protected ShoppingCart() { }

    #endregion
4

2 回答 2

1

将调用静态构造函数only once。所以 else 永远不会执行。

除了这个实现,您可以使用一个属性来检查会话是否为空,它会创建一个实例,否则它会返回存储的实例。

public Instance
{
set{ ... }
get{ ... }
}
于 2012-06-15T04:49:33.653 回答
0

我发现 ShopingCart 类构造函数中存在问题当我直接使用静态构造函数时,我变成了全局的,这就是我的购物车数据与其他用户购物车共享的方式,但现在我正在使用对象的属性。就像这个,

*主要是get属性的if语句中的返回类型*

 public static ShoppingCart Instance
    {
        get
        {
            if (HttpContext.Current.Session["ShoppingCart"] == null)
            {
                // we are creating a local variable and thus
                // not interfering with other users sessions
                ShoppingCart instance = new ShoppingCart();
                instance.Items = new List<CartItem>();
                HttpContext.Current.Session["ShoppingCart"] = instance;
                return instance;
            }
            else
            {
                // we are returning the shopping cart for the given user
                return (ShoppingCart)HttpContext.Current.Session["ShoppingCart"];
            }
        }
    }
于 2012-06-15T05:22:32.677 回答