0

Pro ASP.NET MVC 4 * 4th * Edition By Adam Freemanおよび「Building the Shopping Cart」ページ 219 で、彼はCart Entityを定義しました。

 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」リスト内のこの製品の「 Quantity」プロパティも増加します)。そして私の質問は、この更新 (「lineCollection」の製品Quantityの増加) がどのように発生するかです。「 lineCollection」を直接変更しませんでしたか?

申し訳ありません:

  • 私の悪い英語
  • 私の厄介な質問
4

1 に答える 1

0

line は lineCollection 内のアイテムのコピーではありません。それは実際にはオブジェクトへの参照です。ラインを変更すると、コレクション内のアイテムも変更されます。

于 2013-06-11T23:17:59.487 に答える