创建继承通用默认参数的Collection类

时间:2018-07-13 05:33:39

标签: c# asp.net-core ienumerable

我想在存储库外部创建一个C#类,该类继承所有默认的通用方法(添加,全部删除等)。以下代码有效。我的目标是将List ShoppingCart移至存储库之外。

public class CartLine
{
    public int CartLineId { get; set; }
    public int ProductId { get; set; }
    public int Quantity { get; set; }
}

以下代码工作:

 public class ShoppingCartRepository
    {

        private List<CartLine> ShoppingCart = new List<CartLine>();


        public IEnumerable GetShoppingCart()
        {
            return ShoppingCart.ToList();
        }

        public virtual void AddItem(int productid, int quantity)
        {
            ShoppingCart.Add(new CartLine { ProductId = productid, Quantity = quantity });
        }

        public virtual void RemoveItem(int cartlineid)
        {
            ShoppingCart.RemoveAll(l => l.CartLineId == cartlineid);
        }

此代码无效:“错误:购物车不包含ToList的定义。

public class ShoppingCart : List<ShoppingCart>
{
    public ShoppingCart()
    {
        List<CartLine> ShoppingCart = new List<CartLine>();
    }
}


public class ShoppingCartRepository
{

    //private List<CartLine> ShoppingCart = new List<CartLine>();


    public IEnumerable GetShoppingCart()
    {
        return ShoppingCart.ToList();
    }

    public virtual void AddItem(int productid, int quantity)
    {
        ShoppingCart.Add(new CartLine { ProductId = productid, Quantity = quantity });
    }

    public virtual void RemoveItem(int cartlineid)
    {
        ShoppingCart.RemoveAll(l => l.CartLineId == cartlineid);
    }

}

2 个答案:

答案 0 :(得分:3)

也许这会对您有所帮助。

public class CartLine
{
        public int CartLineId { get; set; }
        public int ProductId { get; set; }
        public int Quantity { get; set; }
}

    public class ShoppingCart : List<CartLine>
    {
        public ShoppingCart()
        {
        }

    }

    public class ShoppingCartRepository
    {

        private ShoppingCart ShoppingCart = new ShoppingCart();

        public IEnumerable GetShoppingCart()
        {
            return ShoppingCart.ToList();
        }

        public virtual void AddItem(int productid, int quantity)
        {
            ShoppingCart.Add(new CartLine
            {
                ProductId = productid,
                Quantity = quantity
            });
        }

        public virtual void RemoveItem(int cartlineid)
        {
            ShoppingCart.RemoveAll(l => l.CartLineId == cartlineid);
        }

    }

我更改类以使其通用。我认为的问题是,您制作了ShoppingCart的通用列表,但想添加CartLine

希望对您有帮助。

答案 1 :(得分:0)

我不确定您为什么要将购物车移至外部,但是代码存在很多问题

  1. 您将需要在List<CartLine> ShoppingCart中定义class ShoppingCartRepository属性。现在,您正在内部构造函数中创建它。这不会成为该类的ShoppingCart属性/字段。
  2. 如以下注释中所述,ToList()不是List的一部分。因此,除非您明确定义它,否则将无法使用它。但不确定为什么需要在ToList()元素上调用List
  3. 此外,您不应继承自List<ShoppingCart>,而应使用接口-IList<T>。这将帮助您进行模拟/测试。

更重要的是,我看不到您尝试做的任何增值。如果您可以提供更多详细信息,也许我可以提供更多详细信息。