【问题标题】:Does Delphi Generics support Lower / Upper Type Bounds?Delphi 泛型是否支持下/上类型边界?
【发布时间】: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


【解决方案1】:

在 Delphi 中,此示例如下所示(去除不相关的代码):

type
  TAnimal = class(TObject);

  TDog = class(TAnimal);

  TPuppy = class(TDog);

  TAnimalCarer = class
    procedure Display<T: TDog>(dog: T);
  end;

var
  animal: TAnimal;
  dog: TDog;
  puppy: TPuppy;
  animalCarer: TAnimalCarer;
begin
//  animalCarer.Display(animal); // [dcc32 Error] E2010 Incompatible types: 'T' and 'TAnimal'
  animalCarer.Display(dog);
  animalCarer.Display(puppy);
end.

无法指定您链接到的文章中所示的下限,因为 Delphi 不支持该下限。它也不支持任何类型变化。

编辑:FWIW 在这种情况下,Display 方法甚至不必是通用的,dog 参数可以只是 TDog 类型,因为您可以传递任何子类型。由于 Delphi 中泛型的功能有限,因此 Display 方法不会从泛型中受益。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2016-09-18
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    相关资源
    最近更新 更多