![](/img/trans.png)
[英]How to access the collection inside a class which inherits Collection<>?
[英]Create Collection class which inherits generic default parameters
我想在存储库外部创建一个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);
}
}
也许这会对您有所帮助。
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
。
希望对您有所帮助。
我不确定您为什么要将购物车移到外面,但是代码有很多问题
List<CartLine> ShoppingCart
class ShoppingCartRepository
定义List<CartLine> ShoppingCart
属性。 现在,您正在内部构造函数中创建它。 那不会使ShoppingCart
成为类的属性/字段。 ToList()
不是List
一部分。 因此,除非您明确定义它,否则将无法使用它。 但不确定为什么需要在List
元素上调用ToList()
。 List<ShoppingCart>
,而应该使用interface- IList<T>
。 这将帮助您进行模拟/测试。 更重要的是,我没有看到您尝试做的任何增值。 如果您可以提供更多详细信息,也许我可以提供更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.