Delphi引用程序异常

在Delphi中,您显然可以将整个方法调用链分配给单个变量:

program What;
{$APPTYPE CONSOLE}

type
  TProc = reference to procedure();

  TRecord = record
    procedure MethodOfRecord();
  end;

procedure TRecord.MethodOfRecord();
begin
  WriteLn('MethodOfRecord finished');
end;

function MakeRecord(): TRecord;
begin
  WriteLn('    MakeRecord finished');
end;

var
  proc: TProc;
begin
  proc := MakeRecord().MethodOfRecord;
  proc();
  proc();
  proc();
end.

In this code, I create an anonymous TRecord, assign its method TRecord.MethodOfRecord to a reference to procedure, and then call it 3 times.

Question: How many times will MakeRecord be called?

答:3次:

    MakeRecord finished
MethodOfRecord finished
    MakeRecord finished
MethodOfRecord finished
    MakeRecord finished
MethodOfRecord finished

Every time I call proc, it calls MakeRecord first. This seems weird. Why does this happen? I expected it to be called only once. Is it because it's anonymous? Of course if I give the TRecord a name, it gets called only once:

var
  proc: TProc;
  rec: TRecord;
begin
  rec := MakeRecord();
  proc := rec.MethodOfRecord;
  proc();
  proc();
  proc();
end.

输出:

    MakeRecord finished
MethodOfRecord finished
MethodOfRecord finished
MethodOfRecord finished

有人可以解释这种行为背后的逻辑吗?这是在某处记录的吗?

这是Embarcadero®Delphi 10.3。

评论