普通方法、类的方法、匿名方法 做参数

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.

 

转载于:https://www.cnblogs.com/del88/p/6929079.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值