2017-04-27 45 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> 
{ 
}