分享

如何把类中的方法做参数

 独孤求财 2012-03-27

问题来源: http://www.cnblogs.com/del/archive/2008/08/15/1268301.html#1806783

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  public
    function MySqr(const num: Integer): Integer; {这是类中的一个方法, 准备做参数使用}
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

Type
  TFun = function(const num: Integer): Integer of object; {定义的类型参数同上}

{这是上面那个方法的实现}
function TForm1.MySqr(const num: Integer): Integer;
begin
  Result := num * num;
end;

{把 TFun 类型的方法做参数}
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.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多