我看到了一本实现购物车的书:
public class Cart
{
private List<CartLine> lineCollection = new List<CartLine>();
public virtual void AddItem(Product product, int quantity){...}
public virtual void RemoveLine(Product product){...}
}
public class CartLine {
public int CartLineID { get; set; }
public Product Product { get; set; }
public int Quantity { get; set; }
}
和从SessionCart
派生的Cart
类
//.GetJson() and .SetJson() are customized extension methods of ISession to serialize and deserialize objects.
public class SessionCart: Cart
{
public static Cart GetCart(IServiceProvider services) {
ISession session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
SessionCart cart = session?.GetJson<SessionCart>("Cart") ?? new SessionCart();
cart.Session = session;
return cart;
}
[JsonIgnore]
public ISession Session { get; set; }
public override void AddItem(Product product, int quantity)
{
base.AddItem(product, quantity);
Session.SetJson("Cart", this);
}
public override void RemoveLine(Product product)
{
base.RemoveLine(product);
Session.SetJson("Cart", this);
}
}
我很困惑,对我而言,SessionCart处理会话对象,难道我们不能将所有与会话相关的代码都移到Cart
类吗,所以我们不需要SessionCart
类吗?