是否可以将记录用作方法参数,并在不隐式声明所述记录的实例的情况下调用它?

我希望能够编写这样的代码。

type
  TRRec = record
    ident : string;
    classtype : TClass;
  end;

procedure Foo(AClasses : array of TRRec);

然后调用这样的方法或类似的方法。

Foo([('Button1', TButton), ('Lable1', TLabel)]);

顺便说一下,我仍然坚持使用Delphi 5。

有帮助吗?

解决方案

是。几乎。

type
  TRRec = record
    ident : string;
    classtype : TClass;
  end;

function r(i: string; c: TClass): TRRec;
begin
  result.ident     := i;
  result.classtype := c;
end;

procedure Foo(AClasses : array of TRRec);
begin
  ;
end;

// ...
Foo([r('Button1', TButton), r('Lable1', TLabel)]);

其他提示

也可以使用const数组,但它不像“gangph”给出的解决方案那么灵活: (特别是你必须在数组声明中给出数组的大小([0..1])。记录是不合理的,数组不是)。

type
  TRRec = record
    ident : string;
    classtype : TClass;
  end;

procedure Foo(AClasses : array of TRRec);
begin
end;

const tt: array [0..1] of TRRec = ((ident:'Button1'; classtype:TButton),
                                   (ident:'Lable1'; classtype:TLabel));

Begin
  Foo(tt);
end.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top