delphi中的匿名记录构造函数
问题描述:
是否可以使用记录作为方法参数,并在不隐式声明所述记录的实例的情况下调用它?delphi中的匿名记录构造函数
我希望能够编写这样的代码。
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)]);
答
也可以用一个常量数组的工作,但它不是那么灵活,因为通过“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.
你的意思是没有明确声明所述记录的一个实例,是吗? ;) – jpfollenius 2009-03-05 12:47:36
也许最好说“匿名记录_initialisers_” – 2013-09-22 07:00:40