Delphi Generics是否支持较低/较高类型的界限?

Ren*_*nop 10 delphi generics type-bounds

Delphi是否支持其泛型的/上类型边界,例如Scala?

我在Embarcadero文档中没有找到任何关于它的内容:

此外,在" 泛型中的约束"中存在对类型边界的隐式提示:

约束项包括:

  • 零,一个或多个接口类型
  • 零或一类类型
  • 保留字"构造函数","类"或"记录"

您可以为约束指定"构造函数"和"类".但是,"记录"不能与其他保留字组合.多个约束充当附加联合("AND"逻辑).

例:

让我们看看下面Scala代码中的行为,它演示了上限类型限制的用法.我在网上找到了这个例子:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在Delphi中实现这样的行为?

Ste*_*nke 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.
Run Code Online (Sandbox Code Playgroud)

如您所链接的文章所示,无法指定下限,因为Delphi不支持.它也不支持任何类型差异.

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