5

在阅读Delphi 匿名方法的文档时,我开始怀疑。我一直使用这样的东西:

type TMathFn = Function(A, B: Integer): Integer;
var fn: TMathFn;

一直为我工作。但是这个文件告诉我改用这个:

type TMathFn = Reference to Function(A, B: Integer): Integer;
var fn: TMathFn;

由于我从 1994 年到 2010 年一直在 Delphi 进行开发,因此我对这个“参考”部分有点陌生。尽管如此,这两种选择似乎都同样有效。所以……
他们是一样的吗?

4

2 回答 2

8

“REFERENCE TO”是允许匿名方法(PROCEDUREs / FUNCTIONs的内联定义),它可以捕获上下文(例如局部变量,它们被捕获为引用,即如果您在捕获后更改变量,它是修改后的值被捕获,见下文)。

TYPE TMyProc = REFERENCE TO PROCEDURE(CONST S : STRING);

PROCEDURE Information(CONST S : STRING);
  BEGIN
    MessageDlg(S,mtInformation,[mbOK],0)
  END;

PROCEDURE RunProc(P : TMyProc ; CONST S : STRING);
  BEGIN
    P(S)
  END;

PROCEDURE A(B,C : INTEGER);
  VAR
    D : INTEGER;
    P : TMyProc;

  BEGIN
    D:=3;
    // D is 3 at the time of capture
    P:=PROCEDURE(CONST S : STRING)
         BEGIN
           Information(S+': '+IntToStr(D)+' -> '+IntToStr(B))
         END;
    // D is now 4 - and is reflected in the captured routine, as
    // the capture is done by REFERENCE and not by VALUE.
    INC(D);
    RunProc(P,'Hello')
  END;

BEGIN
  A(2,3)
END.

将在消息框中显示“Hello: 4 -> 2”。

上述 P 的定义“捕获”(包括)变量 D 和 B ,因此即使您将其传递给另一个函数,而这些变量不存在,您仍然可以访问它们。

这对于普通的 PROCEDURE [OF OBJECT] 类型来说(几乎)是不可能的,因为它们无法访问在执行点声明的局部变量。

于 2020-11-02T10:36:24.637 回答
5

不,它们不相同。

不同之处在于

TMathFn = function(A, B: Integer): Integer;

是一个普通的函数,

TMathMethod = function(A, B: Integer): Integer of object;

是一种方法,并且

TMathAnonMethod = reference to function(A, B: Integer): Integer;

是匿名方法,但您也可以将普通函数或方法分配给这种类型的变量。

因此,例如,如果

type
  TMathFn = function(A, B: Integer): Integer;
  TMathMethod = function(A, B: Integer): Integer of object;
  TMathAnonMethod = reference to function(A, B: Integer): Integer;

function Test(A, B: Integer): Integer;
begin
  Result := A + B;
end;

type
  TTestClass = class
    function Test(A, B: Integer): Integer;
  end;

{ TTestClass }

function TTestClass.Test(A, B: Integer): Integer;
begin
  Result := A + B;
end;

那么以下适用:

procedure TForm1.FormCreate(Sender: TObject);
var
  T: TTestClass;
  F: TMathFn;
  M: TMathMethod;
  AM: TMathAnonMethod;
begin

  T := TTestClass.Create;
  try

    F := Test; // compiles
    F := T.Test; // doesn't compile
    F := function(A, B: Integer): Integer
      begin
        Result := A + B;
      end; // doesn't compile

    M := Test; // doesn't compile
    M := T.Test; // compiles
    M := function(A, B: Integer): Integer
      begin
        Result := A + B;
      end; // doesn't compile

    AM := Test; // compiles
    AM := T.Test; // compiles
    AM := function(A, B: Integer): Integer
      begin
        Result := A + B;
      end; // compiles

  finally
    T.Free;
  end;

end;

正如您可能已经知道的那样,在底层,F它只是一个(函数)指针并且M是一个方法指针。另一方面,匿名方法有一个更复杂的基于接口的实现,这允许它们的所有魔力(如变量捕获)。

于 2020-11-02T10:41:40.250 回答