繁体   English   中英

始终仅将1个项目添加到列表C#

[英]Always add only 1 item to the list C#

我想将对象列表添加到会话中,但是在我的代码中总是创建Fresh Object(列表中总是只有1个项目)

DTO

 public class CartTotal
{
    public decimal SubTotal { get; set; }
    public decimal DeliveryCharges { get; set; }
    public decimal GrandTotal { get; set; }
    public int CurrentItemCount { get; set; }

    public List<Items> items { get; set; }
}

项目

 public class Items
{
    public int ItemId { get; set; }
    public string ItemCode { get; set; }
    public string ItemName { get; set; }
    public string ImageUrl { get; set; }
    public int? ItemBadge { get; set; }
    public DateTime? AddedDate { get; set; }
    public int? AddedBy { get; set; }


}

会议

  public CartTotal ItemsHolder
    {
        get
        {
            object ItemsSession = Session["ItemSession"] as CartTotal;

            if (ItemsSession == null)
            {
                ItemsSession = new CartTotal();
                Session["ItemSession"] = ItemsSession;
            }

            return (CartTotal)ItemsSession;
        }
    }

我试图将商品添加到列表中,如下所示。但总是添加新鲜商品和(列表中始终只有1个商品。)

            ItemsHolder.items = new List<Items>(); // When i comment this line,below code not working.

            ItemsHolder.items.Add(new Items() {
                ItemId = items.ItemId,
                ItemName = items.ItemName,
                ItemPrice = items.ItemPrice,
                ImageUrl = items.ImageUrl,
                ItemCode = items.ItemCode
            });

CartTotal类中,编写

public List<Items> items { get; } = new List<Items>();

这将在每个CartTotal对象中创建一次新列表。 此外, items属性为只读。 因此,您不能无意中将其添加到另一个列表。

删除行

ItemsHolder.items = new List<Items>(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM