使用泛型的 Delphi 属性 getter 函数

mal*_*lom 3 delphi generics properties delphi-xe2

拥有通用属性 getter/setter 来对每次访问执行常见任务会很好。

该代码在 Delphi XE2 'E2008 Incompatible types' 中给出了一个编译时错误。类似的代码在编译期间给出了一个内部错误,但从未编译过。我犯了错误还是编译器限制?

type TFoo = class
private
  function Get<T>: T;
public
  property Bar: Integer read Get<Integer>;
end;

function TFoo.Get<T>: T;
begin
  Result := 0;
end;
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 5

以下内容在 Delphi 语言中可以是通用的:

  • 类,例如 TFooClass<T> = class
  • 记录,例如 TFooRecord<T> = record
  • 接口,例如 TFooInterface<T> = interface
  • 程序类型,例如 TFooProc<T> = procedure
  • 方法,例如 procedure FooMethod<T>()

属性本身不能是通用的,也不能使用通用的 getter 或 setter 方法来实现。