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

标签 delphi generics 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 方法甚至不必是通用的,并且狗参数可以只是 TDog 类型,因为您可以传递任何子类型。由于 Delphi 中泛型的功能有限,Display 方法不会从泛型中受益。

关于delphi - Delphi 泛型是否支持下/上类型界限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52479313/

相关文章:

Delphi 汇编调用

c# - 如何为类的继承者专门化参数类型?

rust - 为什么 `ToString` 项的迭代器要求它们也为 `Display`?

swift 泛型 : Cannot convert value of type to expected argument type

scala - 如何避免 Scala 中类型绑定(bind)的重复

delphi - 如何将字符串参数传递给 TADOQuery?

ios - Delphi:如何修复错误的 SdkTransformAssistant iOS header 转换?

delphi - 什么是 ActiveX 容器?

scala - 当泛型与无界通配符一起使用时,不考虑类型参数绑定(bind)