2013-06-11 160 views
0

临ASP.NET MVC 4 * *版通过亚当·弗里曼和“构建购物车” 219页,他定义一个车实体购物车

public class Cart 
{ 
    private List<CartLine> lineCollection = new List<CartLine>(); 

    public void AddItem(Product product, int quantity) 
    { 
     CartLine line = lineCollection 
      .Where(p => p.Product.ProductId == product.ProductId) 
      .FirstOrDefault(); 

     if (line == null) 
     { 
      lineCollection.Add(new CartLine { Product = product, Quantity = quantity }); 
     } 
     else 
     { 
      line.Quantity += quantity; 
     } 
    } 
     //Other codes 

    public class CartLine { 
     public Product Product { get; set; } 
     public int Quantity { get; set; } 
    } 
} 

这个模型是从调用AddToCart操作方法:

public RedirectToRouteResult AddToCart(Cart cart, int productId, string returnUrl) 
     { 
      Product product = ctx.Products.FirstOrDefault(p => p.ProductId == productId); 

      if (product != null) 
      { 
       cart.AddItem(product, 1); 
      } 

      return RedirectToAction("Index", new { returnUrl }); 
     } 

当第一次我们添加产品到购物车它增加到“lineCollection”列表。但是,如果我们再添加本产品“line.Quantity”的增加和“lineCollection得到更新(“数量‘中的’lineCollection”列表中增加这种产品的特性)。而我的问题是如何更新(增加“linecollection”的产品数量)发生?我们没有直接更改“linecollection”?

对不起,:

  • 我的英语不好
  • 我凌乱的问题

回答

0

线路未lineCollection项目的副本。它真的是对该对象的引用。你改变线,你也改变集合中的项目。

+0

感谢您的帮助。 – Masoud