有没有办法让继承类型的返回类型逆变?请参阅下面的示例代码。我需要这个用于 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; }
}
最佳答案
您可以应用具有相应约束的泛型
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>
{
}
关于c# - 继承中的逆变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43649862/