gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:50:00 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com