Delphi匿名方法(二):使用本地变量

在匿名函数中,可以修改本地变量的值

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs;

type
  TIntSum = reference to procedure (x, y: Integer);

  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    procedure plusXandY(x, y: Integer; intSum: TIntSum);
    { Private declarations }
  public
    { Public declarations }
  end;


var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
  lResult: Integer;
begin

  plusXandY(40,
            30,
            procedure (x, y: Integer)
            begin
              lResult := lResult + x + y;
            end);
  ShowMessageFmt('x + y = %d', [lResult]);    // 调用三次,结果是210

end;

procedure TForm1.plusXandY(x, y: Integer; intSum: TIntSum);
begin
  intSum(x, y);
  intSum(x, y);
  intSum(x, y);

end;

end.

 

 

posted @ 2013-02-21 16:24  静候良机  阅读(530)  评论(0编辑  收藏  举报