如何在c#中创建“1用户1购物车”购物车 [英] how to create '1 user 1 cart' shopping cart in c#

查看:114
本文介绍了如何在c#中创建“1用户1购物车”购物车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个购物车应用程序,如果我将一个项目添加到购物车中,则不同系统/浏览器中的其他用户可以看到它。

我需要1个用户1个购物车代码。



这里是我的代码



i have a shopping cart application, if i add a item into the cart, it is visible to other users in different systems/browsers.
I need 1 user 1 cart code.

here is my code

// shoppingcart.cs class
public class ShoppingCart {
	static ShoppingCart() {
		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"];
		}
	}

	public void AddItem(int productId) {
		CartItem newItem = new CartItem(productId);
		if (Items.Contains(newItem)) {
			foreach (CartItem item in Items) {
				if (item.Equals(newItem)) {
					item.Quantity++;
					return;
				}
			}
		} else {
			newItem.Quantity = 1;
			Items.Add(newItem);
		}
	}
}


// c# code
ShoppingCart.Instance.AddItem(ProductID);

推荐答案

静态的东西只有一个由每个人共享的副本,并且您的静态构造函数只被调用一次(第一次访问ShoppingCart时)。所以基本上第一个使用他们购物车的人都会在他们的会话中创建并存储购物车,然后其他人通过您班级的Instance属性使用该购物车。你基本上使用的是单例模式,这正是你得到的....一个单一的购物车。



你需要在每次访问实例时返回而不是按照你的方式存储它。



Things that are static only have one copy that is shared by everyone and your static constructor is only called once (the first time ShoppingCart is accessed). So basically the first person to use their cart has a cart created and store in their session, and that cart is then used by everyone else via the Instance property of your class. You are basically using a singleton pattern and that is exactly what you're getting....a single cart.

You need to return Instance each time it is accessed rather than storing it the way you are.

static class ShoppingCart()
{
    public static ShoppingCart Instance
    {
        get
        {
            ShoppingCart cart = null;
            if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
            {
                cart = new ShoppingCart();
                cart.Items = new List();
                HttpContext.Current.Session["ASPNETShoppingCart"] = cart;
            }
            else
            {
                cart = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
            }
            return cart;
        }
    }
}


这篇关于如何在c#中创建“1用户1购物车”购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆