1.普通方法做参数:

 

如果方法 是类的方法,那么就不能当函数的参数了,编译会报错,就是说 类的方法的指针 与 普通方法的指针是有区别的,毕竟类的方法的指针 可能包含了 面向对象的 继承 覆盖 等信息;

 

 

2.类的方法做参数,就是说类的方法的类型要加上 of object:

 

 

 

 

 

 

 

 

3.匿名方法 做参数,要加上 reference to

 

 

 

最终的调试代码:

 

unit Unit6;

interface

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

type

  /// <summary>
  /// 普通方法类型
  /// </summary>
  TPuTongFun = function(const num: Integer): Integer;

  /// <summary>
  /// 类的方法的类型
  /// </summary>
  TObjectFun = function(const num: Integer): Integer of object;

  /// <summary>
  /// 匿名方法的类型
  /// </summary>
  TNiMingFun = reference to function(const num: Integer): Integer;

  TForm6 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    /// <summary>
    /// 类的方法
    /// </summary>
    function puTongFun3(const num: Integer): Integer;
  end;

var
  Form6: TForm6;

implementation

{$R *.dfm}

function puTongFun1(const num: Integer): Integer;
begin
  //加法
  Result := num + num;
end;

function puTongFun2(const num: Integer): Integer;
begin
  //乘法
  Result := num * num;
end;

function TForm6.puTongFun3(const num: Integer): Integer;
begin
  //乘以5
  Result := num * 5;
end;

//用普通方法做参数的方法
function abc(const x: Integer; AFun: TPuTongFun): string;
begin
  Result := (AFun(x) + 1).ToString;
end;

//用类的方法做参数的方法
function abcObject(const x: Integer; AFun: TObjectFun): string;
begin
  Result := (AFun(x) + 1).ToString;
end;

//匿名方法类型做参数
function abcNiMing(const x: Integer; AFun: TNiMingFun): string;
begin
  Result := (AFun(x) + 1).ToString;
end;

procedure TForm6.Button1Click(Sender: TObject);
var
  pu1,pu2: TPuTongFun;
  pu3: TObjectFun;
  pu4: TNiMingFun;
begin
  //初始化实例(可以根据情况选择方法的实例)
  pu1 := puTongFun1;{用加法}
  pu2 := puTongFun2;{用乘法}
  pu3 := puTongFun3;{类的方法-乘以5}

  //匿名方法的实例创建
  pu4 := function(const num: Integer): Integer {注意本行最后不能有 ; 号}
  begin
    Result := num * 6;
  end;


  //结果
  ShowMessage(abc(3, pu1)); {7}
  ShowMessage(abc(3, pu2)); {10}
  ShowMessage(abcObject(3, pu3)); {16}
  ShowMessage(abcNiMing(3, pu4)); {19}
end;


end.

 

posted on 2017-06-01 15:25  del88  阅读(332)  评论(0编辑  收藏  举报