将常量传递给作为开放记录数组的函数参数

Passing constants to a function parameter that is an open array of record

我有这样定义的记录:

TRec = record
  S: string;
  I: Integer;
end;

我可以像这样初始化这个记录类型的常量:

const
  Rec: TRec = (S:'Test'; I:123);

现在我有一个函数接受这种记录类型的开放数组:[​​=14=]

function Test(AParams: array of TRec);

我可以使用与常量声明类似的语法调用此函数吗?

Test([(S:'S1'; I:1), (S:'S2'; I:2)]);

这不起作用。我应该使用其他东西吗?

向记录类型添加一个构造函数,它接受所需的参数。

TRec = record
  s : string;
  i : integer;
  constructor create( s_ : string; i_: integer );
end;

constructor TRec.create( s_ : string; i_: integer );
begin
  s := s_;
  i := i_;
end;

procedure test( recs_ : array of TRec );
var
  i : Integer;
  rec : TRec;
begin
  for i := 0 to high(recs_) do
    rec := recs_[i];
end;

procedure TForm1.Button1Click( sender_ : TObject );
begin
  test( [TRec.create('1',1), TRec.create('2',2)] );
end;

正如 Remy Lebeau 所反映的那样,它仅适用于 Delphi 2006 或更新版本。如果您有一个较旧的 IDE,您应该创建一个实用程序 class,其方法(以及其他方法) 符合上面的记录构造函数:

TRecUtility = class
  public
    class function createRecord( s_ : string; i_: integer ) : TRec;
    //... other utility methods
end;

procedure foo;
begin
  test( [TRecUtility.createRec('1',1), TRec.createRec('2',2)] ); 
end;