繁体   English   中英

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

[英]C# Declaring Type Definition Cannot create an instance of the abstract class or interface

我创建了一个类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

最简单的解决方案是创建一个名为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();

该错误不言自明。 两种选择-您可以使用具体类型(例如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( ... ) );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM