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

标签 delphi record open-array-parameters

我有一个这样定义的记录:

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

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

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

现在我有一个函数,它采用这种记录类型的开放数组:

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 所反射(reflect)的,它仅适用于 Delphi 2006 或更高版本。如果您有较旧的 IDE,您应该创建一个实用程序类,其中的方法(以及其他方法)符合上面的记录构造函数:

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;

关于delphi - 将常量传递给作为开放记录数组的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42854766/

相关文章:

java - 如何提取部分录制的音频字节

sql - 将函数返回的记录拆分为多列

delphi - 无法将类型化字符数组传递给打开的字符数组?

record - Ada 中的歧视记录是什么?

arrays - 为什么将开放数组参数转换为数组类型会导致 E2089 无效类型转换?

delphi - 使用 Ant 配置 Sonar 模块的 build.xml 文件

delphi - "Size of published set ' %s ' is >4 bytes"。如何修复这个编译器错误?

delphi - 未找到 .pas 文件,但 .dcu 存在,这还不够吗?

delphi - 针对 17 年以上无法测试的 Delphi 代码的重构计划