2017-04-27 7 views
3

継承された型の反復型を反例にする方法はありますか?以下のサンプルコードを参照してください。私はEntity Frameworkのためにこれが必要です。継承のコントラバナンス

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> 
{ 
}