继承中的逆变

spo*_*r94 1 c# generics entity-framework contravariance

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

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; }
}
Run Code Online (Sandbox Code Playgroud)

Ran*_*dom 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>
{
}
Run Code Online (Sandbox Code Playgroud)