Delphi匿名方法(三):扩展本地变量的生命周期
本地变量,一般是随着函数执行结束,就不能再访问;
而如果在匿名函数,访问了外部函数的本地变量,本地变量的生命周期会被扩展
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TIntSum = reference to procedure (x, y: Integer); TForm1 = class(TForm) btn1: TButton; procedure FormCreate(Sender: TObject); procedure btn1Click(Sender: TObject); private FIntSum: TIntSum; procedure plusXandY(x, y: Integer); { Private declarations } public property IntSum: TIntSum read FIntSum write FIntSum; { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btn1Click(Sender: TObject); begin //点击button1,lResult变成130,第二次变成160,。。。 plusXandY(10, 20); end; procedure TForm1.FormCreate(Sender: TObject); var lResult: Integer; begin //初始化lResult lResult := 100; //将方法制定给属性,但不调用 IntSum := procedure (x, y: Integer) begin lResult := lResult + x + y; ShowMessageFmt('x + y = %d', [lResult]); end; end; procedure TForm1.plusXandY(x, y: Integer); begin intSum(x, y); end; end.