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 は決して実行されません。

この実装の代わりに、セッションが null かどうかをチェックしてインスタンスを作成するプロパティを使用できます。それ以外の場合は、保存されたものを返します。

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 に答える