C#声明类型定义无法创建抽象类或接口的实例

时间:2018-10-14 04:58:48

标签: c# asp.net-core

我创建了一个Cartline类。然后,我创建了一个名为ShoppingCart的集合。 当我尝试声明ShoppingCart时,出现错误。有人知道要解决此问题吗?

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


using ShoppingCart = System.Collections.Generic.IEnumerable<ElectronicsStore.Models.CartLine>;

ShoppingCart shoppingcart = new ShoppingCart();

Cannot create an instance of the abstract class or interface 'IEnumerable<CartLine>'    ElectronicsStore

2 个答案:

答案 0 :(得分:2)

最简单的解决方案是创建一个名为ShoppingCart的新类,该类具有一个属性,该属性是CartLine实体的列表:

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

public class ShoppingCart
{
    public IList<CartLine> CartLines {get;set;}
}


ShoppingCart shoppingcart = new ShoppingCart();

答案 1 :(得分:2)

该错误不言自明。两种选择-您可以使用具体类型(例如List<CartLine>)创建别名,但我建议您定义一个从List<CartLine>继承的类(或最适合您需要的任何集合):

public class ShoppingCart : List<CartLine>
{
    // implement constructors you want available
    public ShoppingCart(){}

    public ShoppingCart( IEnumerable<CartLine> collection ) : base( collection ) {}

    public ShoppingCart( int capacity ) : base( capacity ) {}

    // the benefit here is you can add useful properties
    // if CartLine had a price you could add a Total property, for example:
    public decimal Total => this.Sum( cl => cl.Quantity * cl.Price );
}

然后您可以根据要求使用:

var cart = new ShoppingCart();
cart.Add( new CartLine() { ... } );
var cartTotal = cart.Total;
... etc ...

集合初始化程序也将起作用:

var cart = new ShoppingCart() { new CartLine() { ... }, ... }

或使用现有的IEnumerable<CartLine>进行初始化,例如IQueryable<CartLine>使用实体框架:

var cart = new ShoppingCart( dbContext.CartLines.Where( ... ) );