早期的Delphi版本是没有匿名函数的,不过可以定义一个函数类型来实现类似的功能;后期的版本已经支持匿名函数,随用随写。Go天生就支持匿名函数。
Delphi
函数类型
//声明函数类型
type
TMyProc = procedure(A: Integer); //过程
TMyFunc = function(x: Integer): Integer; //函数
//定义符合函数类型的函数
procedure MyProc(A: Integer);
begin
ShowMessage(IntToHex(A));
end;
function MyFunc1(x: Integer): Integer;
begin
Result := x + x;
end;
function MyFunc2(x: Integer): Integer;
begin
Result := x * x;
end;
//使用
var
mp: TMyProc;
mf: TMyFunc;
begin
mp := MyProc;
mf := MyFunc1;
mp(mf(99));
end;
//作为参数进行传递,这才是函数类型最主要的使用方法
procedure Test(x: Integer; Func: TMyFunc);
begin
ShowMessage(Func(x).ToString);
end;
Test(123, MyFunc1);
Test(123, MyFunc2);
回调函数是函数类型最典型的应用,类的事件可以看作是特殊的回调函数。
匿名函数
匿名函数的好处是可以随用随写,而不必事先把可能用到的实现都写好,而且尽可能把代码块的作用域缩到最小。
//定义匿名函数类型
type TF = reference to function(n: Integer): string;
//使用
var f: TF;
begin
f :=
function(a: Integer): string //注意,此处无分号
begin
Result := a.ToString;
end;
ShowMessage(f(123));
f := nil; //匿名函数内代码的作用域到再次给匿名函数变量赋值为止
end;
匿名函数的用法与函数类型的用法一致。另外,Delphi已经提供好了几个常用的匿名函数类型:TProc、TProc、TProc<T1,T2>、TProc<T1,T2,T3>、TProc<T1,T2,T3,T4>、TFunc、TFunc<T,TResult>、TFunc<T1,T2,TResult>、TFunc<T1,T2,T3,TResult>、TFunc<T1,T2,T3,T4,TResult>和TPredicate。
Delphi还有一种常见的缩小函数作用域的写法,作用域是整个调用函数内,比匿名函数的作用域略大:
procedure Test(x: Integer);
function Func(A: Integer): Integer; //整个Test函数内均可调用
begin
Result := A * A;
end;
begin
ShowMessage(Func(x).ToString);
end;