2017-04-27 44 views
3

有没有办法在继承类型中产生返回类型的逆变?请参阅下面的示例代码。我需要这个实体框架。继承的逆变

public class InvoiceDetail 
{ 
    public virtual ICollection<Invoice> Invoices { get; set; } 
} 

public class SalesInvoiceDetail : InvoiceDetail 
{ 
    //This is not allowed by the compiler, but what we are trying to achieve is that the return type 
    //should be ICollection<SalesInvoice> instead of ICollection<Invoice> 
    public override ICollection<SalesInvoice> Invoices { get; set; } 
} 

回答

5

您可以将仿制药与相应的约束

public abstract class InvoiceDetailBase<T> where T : Invoice 
{ 
    public virtual ICollection<T> Invoices { get; set; } 
} 

public class InvoiceDetail : InvoiceDetailBase<Invoice> 
{ 
} 

public class SalesInvoiceDetail : InvoiceDetailBase<SalesInvoice> 
{ 
}