以下代码(仅为演示问题而构建)在 Delphi 2010 中编译并运行。在 Delphi 2009 中,编译器失败并显示“E2035 实际参数不足”。
program Project50;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TMyProc = reference to procedure(param: integer);
var
a: TProc;
b: TMyProc;
begin
b := procedure (param: integer)
begin
end;
a := TProc(b); // <-- [DCC Error] Project50.dpr(19): E2035 Not enough actual parameters
end.
我发现只有一个非常丑陋的 hack 可以解决这个问题(a:TProc 绝对 b)。有人知道针对这个编译器缺陷的更好的解决方法吗?
[TProc 字段实际上隐藏在可以存储各种“可执行”代码的记录内 - TProcedure、TMethod 和 TProc。转换用于将特定的匿名过程存储到该字段中。]
最佳答案
诀窍是不做
a := TProc(b);
但是
TMyProc(a) := b;
可以在 D2009 中编译并运行。下面附有示例项目。
program Project51;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TMyProc = reference to procedure(var param: integer);
TStorage = record
FDelegate: TProc;
end;
var
a : TMyProc;
b : TMyProc;
param: integer;
stg : TStorage;
begin
b := procedure (var param: integer)
begin
param := 2*param;
end;
// stg.FDelegate := TMyProc(b); // doesn't compile in Delphi 2009, compiles in Delphi 2010
TMyProc(stg.FDelegate) := b;
param := 21;
TMyProc(stg.FDelegate)(param);
Writeln(param);
Readln;
end.
但是,如果转换为局部变量,则这不起作用。
var
p: TProc;
a: TMyProc;
TMyProc(p) := a; // this will not compile
越来越好奇。
关于delphi - 在 Delphi 2009 中类型转换匿名过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2307262/