您的位置:首页 > 编程语言 > Delphi

delphi 精要-读书笔记(过程类型,方法类型)

2006-06-13 20:24 453 查看
下面是对两种数据类型的认识(过程类型,方法类型)

1.过程类型

unit Unit1;

interface

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

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);

private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}
type
TOneFun=function(X:Integer):Integer;

function SomeFunction(X:Integer):Integer;
begin
Result:=X*2
end;

function SomeCallBack(X:Integer;OneFun:TOneFun):Integer; //这个相当于一个回调函数
begin
Result:=OneFun(X);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
F:TOneFun;
I,J:Integer;
begin
F:=SomeFunction;
I:=F(4);
j:=SomeCallBack(4,F);
if i=j then
showmessage('F(4)和SomeCallBack功能相同');
showmessage(inttostr(i));
showmessage(inttostr(j));
end;

end.

2.方法类型

unit Unit1;

interface

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

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure ShowInfo;
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

{
方法指针可以用定义在System单元的一个记录描述
type
TMethod=record
code,data :Pointer;

它包含两个指针code和data,code可以看作是方法地址的指针,data可以看做是方法所属对
象的指针
}

procedure TForm1.Button1Click(Sender: TObject);
type
TMyProcedure=procedure of object; //定义了一个方法类型
var
OneProcedure:TMyProcedure; //声明一个方法类型的变量
begin
OneProcedure:=Form1.ShowInfo; //给方法指针赋值
{
也可以这样给方法指针赋值
TMethod(OneProcedure).code:=Form1.MethodAddress('showinfo');
TMethod(OneProcedure).data:=Form1;
}
ShowMessage(TObject(TMethod(OneProcedure).Data).ClassName);
OneProcedure;
end;

procedure TForm1.ShowInfo;
begin
ShowMessage(Self.Name);
end;

end.

过程类型的变量是指向过程的指针,和回调函数差不多,方法类型的变量是指向方法的指针,写法上还比过程类型多了 of objects,方法类型的变量只能通过对象来引用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: