Delphi 泛型是否支持类型上限/下限?

Does Delphi Generics support Lower / Upper Type Bounds?

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

我在 Embarcadero 文档中没有找到任何相关信息:

此外,在“泛型约束”处有一个针对类型边界的隐式提示:

Constraint items include:

  • Zero, one, or multiple interface types
  • Zero or one class type
  • The reserved word "constructor", "class", or "record"

You can specify both "constructor" and "class" for a constraint. However, "record" cannot be combined with other reserved words. Multiple constraints act as an additive union ("AND" logic).

示例:

让我们看一下以下 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 中实现这种行为吗?

在 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 方法不会因泛型而受益。