delphi 精要-讀書筆記(過程類型,方法類型)

來源:互聯網
上載者:User

下面是對兩種資料類型的認識(過程類型,方法類型)

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,方法類型的變數只能通過對象來引用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.