【问题标题】:constraining a generic type at absract class level or interface level在抽象类级别或接口级别约束泛型类型
【发布时间】:2021-02-18 18:51:30
【问题描述】:

我想将泛型类型限制为特定类型。在这种情况下,我希望泛型类型 T 属于 IComparable。我希望限制发生在父类级别(或父接口级别)。这是示例代码:

abstract class BaseContainer<T> where T : IComparable<T> {
    protected List<T> container;
}

class QueueCustom<T> : BaseContainer<T>  {
    public QueueCustom() {
        this.container = new List<T>();
    }
}

这会引发错误:

类型“T”不能用作泛型类型中的类型参数“T” 或方法“BaseContainer”。没有拳击转换或类型 从 'T' 到 'System.IComparable' 的参数转换。

我可以在子类级别限制类型 T:

abstract class BaseContainer<T> {
    protected List<T> container;
}

class QueueCustom<T> : BaseContainer<T> where T : IComparable<T>   {
    public QueueCustom() {
        this.container = new List<T>();
    }
}

我如何在父类而不是派生类中做呢?

【问题讨论】:

  • 您需要在父级和所有通用子级执行此操作。所以` BaseContainer where T : IComparable` 和QueueCustom&lt;T&gt; : BaseContainer&lt;T&gt; where T : IComparable&lt;T&gt;

标签: c# .net generics


【解决方案1】:

两者都可以。

通过使用class QueueCustom : BaseContainer,您声明了一条语句“为派生类选择的类型也将是基类的类型”。

这意味着,为了满足基类的要求,你也必须要求它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2021-11-28
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    相关资源
    最近更新 更多