5

以下代码(仅用于演示问题)在 Delphi 2010 中编译和工作。在 Delphi 2009 中,编译器失败并显示“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.

我发现只有一个非常丑陋的黑客可以解决这个问题(a:TProc absolute b)。有没有人知道这个编译器缺陷的更好的解决方法?

[TProc 字段实际上隐藏在可以存储各种“可执行”代码的记录中 - TProcedure、TMethod 和 TProc。Casting 用于将特定的匿名 proc 存储到此字段中。]

4

3 回答 3

2

诀窍是不做

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

越来越好奇。

于 2010-02-22T08:44:27.353 回答
1

我发现了一个 hack #2:

program Project1;

{$APPTYPE CONSOLE}


uses
  SysUtils;

type
  TMyProc = reference to procedure(param: integer);

var
  a: TProc;
  b: TMyProc;

begin
  b := procedure (param: integer)
    begin
      Writeln('asdf');
    end;
  PPointer(@a)^ := PPointer(@b)^;
  a;
  readln;
end.

我怀疑你想通过将 TMyProc (带参数参数)分配给 TProc (不带参数)来实现什么?


更新:A hack #3(应该增加 ref 计数器,这个想法是从 System._IntfCopy 偷来的):

procedure AnonCopy(var Dest; const Source);
var
  P: Pointer;

begin
  P:= Pointer(Dest);
  if Pointer(Source) <> nil
    then IInterface(Source)._AddRef;
  Pointer(Dest):= Pointer(Source);
  if P <> nil then
    IInterface(P)._Release;
end;

var
  a: TProc;
  b: TMyProc;

begin
  b := procedure (param: integer)
    begin
      Writeln('asdf');
    end;
  AnonCopy(a, b);
//  PPointer(@a)^ := PPointer(@b)^;
  a;
  readln;
end.
于 2010-02-21T23:08:11.570 回答
1

似乎最好的方法是使用泛型在记录中存储正确类型的委托。无需破解。

program Project51;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TMyProc = reference to procedure(var param: integer);

  TStorage<T> = record
    FDelegate: T;
  end;

var
  a    : TMyProc;
  b    : TMyProc;
  p    : TProc;
  param: integer;
  stg  : TStorage<TMyProc>;

begin
  b := procedure (var param: integer)
    begin
      param := 2*param;
    end;
  stg.FDelegate := b;
  param := 21;
  stg.FDelegate(param);
  Writeln(param);
  Readln;
end.
于 2010-02-22T08:58:00.883 回答