【发布时间】:2018-09-24 12:22:30
【问题描述】:
Delphi 是否支持 lower / upper type bounds 的泛型,例如像 Scala 那样?
我在 Embarcadero 文档中没有找到任何关于它的信息:
此外,“泛型中的约束”有一个针对类型边界的隐含提示:
约束项包括:
- 零、一种或多种接口类型
- 零或一类类型
- 保留字“constructor”、“class”或“record”
您可以为约束同时指定“构造函数”和“类”。 但是,“记录”不能与其他保留字组合。 多个约束充当加法联合(“AND”逻辑)。
示例:
让我们看看下面的 Scala 代码中的行为,它演示了上限类型限制的用法。我找到了那个例子on the net:
class Animal
class Dog extends Animal
class Puppy extends Dog
class AnimalCarer{
def display [T <: Dog](t: T){ // Upper bound to 'Dog'
println(t)
}
}
object ScalaUpperBoundsTest {
def main(args: Array[String]) {
val animal = new Animal
val dog = new Dog
val puppy = new Puppy
val animalCarer = new AnimalCarer
//animalCarer.display(animal) // would cause a compilation error, because the highest possible type is 'Dog'.
animalCarer.display(dog) // ok
animalCarer.display(puppy) // ok
}
}
有没有办法在 Delphi 中实现这样的行为?
【问题讨论】:
-
我想你想要contravariance。
-
@erip Delphi 不支持协变或逆变。
标签: delphi generics type-bounds