之前我們可以定義方法類型, 然後通過方法類型的變量來使用方法, 譬如: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 = function(const num: Integer): Integer; {先定義一個方法類型}
function MySqr(const num: Integer): Integer; {再創建一個吻合上面類型的一個方法}
begin
Result := num * num;
end;
{測試}
procedure TForm1.FormCreate(Sender: TObject);
var
fun: TFun; {方法變量}
n: Integer;
begin
fun := MySqr; {給變量賦值為相同格式的方法}
n := fun(9); {現在這個方法變量可以使用了}
ShowMessage(IntToStr(n)); {81}
end;
end.unit Unit1;
現在 Delphi 2009 可以使用匿名方法了(使用 reference 定義方法類型, 然後在代碼中隨用隨寫方法), 譬如:
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 = function(const num: Integer): Integer; {先定義一個方法類型}
function MySqr(const num: Integer): Integer; {再創建一個吻合上面類型的一個方法}
begin
Result := num * num;
end;
{把方法當作參數的方法}
procedure MyProc(var x: Integer; fun: TFun);
begin
x := fun(x);
end;
{測試}
procedure TForm1.FormCreate(Sender: TObject);
var
n: Integer;
begin
n := 9;
MyProc(n, MySqr);
ShowMessage(IntToStr(n)); {81}
end;
end.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; {用 reference 定義匿名方法類型}
procedure TForm1.FormCreate(Sender: TObject);
var
fun: TFun;
n: Integer;
begin
{求平方}
fun := function(const a: Integer): Integer {注意本行最後不能有 ; 號}
begin
Result := a * a;
end;
n := fun(9);
ShowMessage(IntToStr(n)); {81}
{求倍數}
fun := function(const a: Integer): Integer
begin
Result := a + a;
end;
n := fun(9);
ShowMessage(IntToStr(n)); {18}
end;
end.
把匿名方法當作其他方法的參數: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.