C# - 如何指定继承层次的多级泛型类型的限制? [英] C# - How to specify generic type constraints for multiple level of inheritance hierarchy?

查看:1104
本文介绍了C# - 如何指定继承层次的多级泛型类型的限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的类层次结构

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>
{
}

当我尝试建立下面的类,我得到的编译错误

When I try to build following class I get compilation error

public class EmployeesQuery : IQuery<SeasonTicketLoan>
{
}



我得到一个错误说 SeasonTicketLoan 类不满足约束。

推荐答案

收益类也应该有一个泛型类型 - 所以所有的父类都在终极 /密封型作为其泛型类型。只有最终/密封类型有没有通用的参数。
结果的结果是,在所有的父类的所有方式,通过到根父类泛型参数包含终极/密封类的种类和出现任何错误。

The Benefit class also should have a generic type - so all parent classes have the "ultimate"/sealed type as their generic type. Only the "ultimate"/sealed types have no generic arguments.
The result is that in all parent classes all way through to the root parent class the generic argument contains the type of the "ultimate"/sealed class and no errors arise.

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# - 如何指定继承层次的多级泛型类型的限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆