我想在存储库外部创建一个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);
}
}
答案 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)
我不确定您为什么要将购物车移至外部,但是代码存在很多问题
List<CartLine> ShoppingCart
中定义class ShoppingCartRepository
属性。现在,您正在内部构造函数中创建它。这不会成为该类的ShoppingCart
属性/字段。ToList()
不是List
的一部分。因此,除非您明确定义它,否则将无法使用它。但不确定为什么需要在ToList()
元素上调用List
。List<ShoppingCart>
,而应使用接口-IList<T>
。这将帮助您进行模拟/测试。更重要的是,我看不到您尝试做的任何增值。如果您可以提供更多详细信息,也许我可以提供更多详细信息。