我有以下类层次结构
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/