Delphi Generics是否支持上下边界?

时间:2018-09-24 12:22:31

标签: delphi generics type-bounds

Delphi是否支持lower / upper type bounds的泛型,例如像Scala一样?

我在Embarcadero文档中没有找到任何有关此事的信息

此外,“ 泛型约束”中有一个隐式类型边界提示:

  

约束项包括:

     
      
  • 零,一种或多种界面类型
  •   
  • 零或一种班级类型
  •   
  • 保留字“构造函数”,“类”或“记录”
  •   
     

您可以为约束指定“构造函数”和“类”。   但是,“记录”不能与其他保留字结合使用。   多个约束充当累加并集(“与”逻辑)。

示例:

让我们看一下以下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中有什么方法可以实现这种行为?

1 个答案:

答案 0 :(得分:13)

在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方法将无法受益于泛型。