下面是對兩種資料類型的認識(過程類型,方法類型)
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,方法類型的變數只能通過對象來引用