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

本文对比分析了过程类型和方法类型的使用方式与特点。过程类型的变量作为指向过程的指针,类似于回调函数;而方法类型的变量则指向方法,并且需要通过对象来引用。通过具体的Delphi代码示例展示了如何定义和使用这两种类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是对两种数据类型的认识(过程类型,方法类型)

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,方法类型的变量只能通过对象来引用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值