在 Delphi 2009 中铸造匿名过程
以下代码(仅为演示问题而构建)在 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。转换用于将特定的匿名过程存储到该字段中。]
The following code (constructed only to demonstrate the problem) compiles and works in Delphi 2010. In Delphi 2009, compiler fails with "E2035 Not enough actual parameters".
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.
I have found only one very ugly hack to work around the problem (a: TProc absolute b). Does anybody knows of a nicer workaround for this compiler deficiency?
[TProc field is actually hidden inside a record that can store various 'executable' code - TProcedure, TMethod and TProc. Casting is used to store specific anonymous proc into this field.]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
诀窍是不这样做
,但
可以在 D2009 中编译并运行。下面附有示例项目。
但是,如果转换为局部变量,则这不起作用。
越来越好奇。
The trick is not to do
but
That compiles and works in D2009. Sample project attached below.
However, this doesn't work if casting to a local variable.
Curiouser and curiouser.
我发现了一个 hack #2:
我怀疑你想通过将 TMyProc (带参数参数)分配给 TProc (不带参数)来实现什么目的?
更新:黑客 #3(应该增加引用计数器,这个想法是从 System._IntfCopy 窃取的):
I have found a hack #2:
I am in doubt what are you trying to achieve by assigning TMyProc (with param argument) to TProc (without argument)?
Updated: A hack #3 (should increment ref counter, the idea is stolen from System._IntfCopy):
看来最好的方法是使用泛型在记录中存储正确的委托类型。无需黑客攻击。
It appears that the best way would be to use generics to store the correct type of delegate in the record. No hacks required.