c# - 继承中的逆变

标签 c# entity-framework generics contravariance

有没有办法让继承类型的返回类型逆变?请参阅下面的示例代码。我需要这个用于 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/

相关文章:

java - 分层HashMap N阶HMM实现

c# - Azure 网站上的 SQLXML

javascript - Angular.js 的 ASP.NET 捆绑和缩小错误

c# - WIQL 树查询从单个子 ID 获取所有父工作项?

c# - 带有 null 的字符串如何给出除 null 之外的其他结果

c# - Entity Framework 规范模式实现

c# - System.Diagnostics.Process.Start 奇怪的行为

entity-framework - Entity Framework 、SQL Server CE 4.0 和 Code First 的启动性能问题

java - 使用 EL 访问继承的属性/方法时出错

c# - 在 C# 中继承泛型的一个很好的理由