C# - 如何为多级继承层次结构指定泛型类型约束?

标签 c# generics

我有以下类层次结构

public class EntityBase<T> where T : EntityBase<T>
{
    //nothing interesting here
}

public class Benefit : EntityBase<Benefit>
{
    //again, nothing interesting here
}

public class SeasonTicketLoan : Benefit
{
    //nothing interesting here
}

现在我得到了如下界面

public interface IQuery<T> where T : EntityBase<T>
{
}

当我尝试构建以下类时出现编译错误

public class EmployeesQuery : IQuery<SeasonTicketLoan>
{
}

我收到一条错误消息,提示 SeasonTicketLoan 类不满足约束条件。

最佳答案

Benefit 类也应该有一个通用类型——因此所有父类都将"ultimate"/sealed 类型作为它们的通用类型。只有“最终”/密封类型没有通用参数。
结果是,在所有父类中一直到根父类,泛型参数包含“最终”/密封类的类型,并且不会出现错误。

public class EntityBase<T> where T : EntityBase<T>
{
    //nothing interesting here
}

public class Benefit<T> : EntityBase<T> where T : Benefit<T>
{
    //again, nothing interesting here
}

public sealed class SeasonTicketLoan : Benefit<SeasonTicketLoan>
{
    //nothing interesting here
}

关于C# - 如何为多级继承层次结构指定泛型类型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29316762/

相关文章:

Java 泛型 : Question regarding type capture and generated inference using generic methods

c# - 如何使用 C# 泛型来简化对 WinRT 设置的访问?

c# - 如何通过脚本使 Texture2D 可读

文件夹 App_Code 中的 C# 访问类

c# - 条件断点在 Visual Studio 2015 中不起作用

typescript - 声明一个构造函数以从 TypeScript 中的 (keyof) 参数正确推断泛型类型

.net - 当 Type 为 TimeSpan 时尝试解析通用类型时出错

c# - 使用数组填充列表框?

c# - 业务对象数据访问层的最佳 "pattern"

delphi - 按需跳过通用参数