Delphi 助手范围

Delphi helpers scope

我在 Delphi 中重新声明助手有问题。

HelperDecl.pas

unit HelperDecl;

interface

type
  TCustomField = Word;

  TCustomFieldHelper = record helper for TCustomField
  public
    procedure SampleMethod();
  end;

implementation

procedure TCustomFieldHelper.SampleMethod();
begin
end;

end.

ScopeTest.pas

unit ScopeTest;

interface

uses HelperDecl;

type
  rec = record
    art: TCustomField;
  end;

implementation

uses System.SysUtils;

procedure DoScopeTest();
var
  a: TCustomField;
  r: rec;
begin
  a := r.art;
  r.art.SampleMethod(); //Here has the compiler no problems
  a.SampleMethod(); //Undeclared identifier 'SampleMethod'
end;

end.

但是我只为我的本地数据类型定义了一个助手(是的,它是从 Word 派生的)! SysUtils 中的助手是 Word 的助手,不是我的自定义数据类型!放开我的数据类型!

当我将 uses System.SysUtils; 移动到 uses HelperDecl; 之前时,它就起作用了。但是我想要一个任意单位的使用顺序。

问题是 TCustomFieldWord 是同一类型,不可能有两个记录助手用于同一类型。

如果您改为让 TCustomField 成为 distinct 类型,它将起作用:

type
  TCustomField = type Word;

Delphi 只支持单助手。当范围内有多个助手时,将使用最近范围的助手。

You can define and associate multiple helpers with a single type. However, only zero or one helper applies in any specific location in source code. The helper defined in the nearest scope will apply. Class or record helper scope is determined in the normal Delphi fashion (for example, right to left in the unit's uses clause).

Class and Record Helpers