【发布时间】: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<T> : BaseContainer<T> where T : IComparable<T>