【发布时间】:2018-07-13 05:33:38
【问题描述】:
我想在存储库之外创建一个 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);
}
}
【问题讨论】:
-
你必须实现缺少的方法。
-
“默认的泛型方法”是什么意思?特别是“默认”部分?
标签: c# asp.net-core ienumerable