把匿名方法當作其他方法的參數:unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
Type
TFun = reference to function(const num: Integer): Integer;
function FunTest(const n: Integer; fun: TFun): string;
begin
Result := Format('%d, %d', [n, fun(n)]);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
f: TFun;
s: string;
begin
f := function(const a: Integer): Integer {注意本行最後不能有 ; 號}
begin
Result := a * a;
end;
s := FunTest(9, f);
ShowMessage(s); {9, 81}
end;
end.