C#-如何为多级继承层次结构指定泛型类型约束?
我有下面的类层次结构C#-如何为多级继承层次结构指定泛型类型约束?,c#,generics,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 { //
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
}
公共类EntityBase,其中T:EntityBase
{
//这里没什么有趣的
}
公共类福利:EntityBase
{
//再说一遍,这里没什么有趣的
}
公共类季票:收益
{
//这里没什么有趣的
}
现在我有以下界面
public interface IQuery<T> where T : EntityBase<T>
{
}
公共接口IQuery,其中T:EntityBase
{
}
当我试图构建下面的类时,我得到了编译错误
public class EmployeesQuery : IQuery<SeasonTicketLoan>
{
}
public class EmployeesQuery:IQuery
{
}
我得到一个错误,说
季票Loan
类不满足约束。福利类也应该有一个泛型类型-因此所有父类的泛型类型都是“ultimate”/sealed类型。只有“ultimate”/“sealed”类型没有泛型参数。
结果是,在从根父类一直到根父类的所有父类中,泛型参数都包含“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
}
公共类EntityBase,其中T:EntityBase
{
//这里没什么有趣的
}
公共类福利:EntityBase,其中T:福利
{
//再说一遍,这里没什么有趣的
}
公共密封类季票:福利
{
//这里没什么有趣的
}
当然不是,因为季票Loan
是(间接)从EntityBase
继承的,而不是EntityBase
。