现在的位置: 首页 > 综合 > 正文

理解 Delphi 的类(四) – 初识类的事件

2011年07月19日 ⁄ 综合 ⁄ 共 1031字 ⁄ 字号 评论关闭
先勾画一下思路:
1、建立一个类, 里面有年龄字段 FAge;
2、通过 Age 属性读写 FAge;
3、如果输入的年龄刚好是 100 岁, 将会激发一个事件, 这个事件我们给它命名为: OnHundred

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  end;

  {先定义一个特殊的类型: 一个对象所属的过程类型; 这是建立一个事件的前提}
  TMyEvent = procedure of object;

  {TMyClass 类}
  TMyClass = class
  strict private
    FAge: Integer;           {年龄字段}
    FOnHundred: TMyEvent;    {为我们刚刚定义的 TMyEvent 类型指定一个变量: FOnHundred}
    procedure SetAge(const Value: Integer);
  public
    procedure SetOnHundred1; {建立事件将要调用的过程}
    procedure SetOnHundred2; {建立事件将要调用的过程}
    constructor Create;
    property Age: Integer read FAge write SetAge;
    property OnHundred: TMyEvent read FOnHundred write FOnHundred; {其实事件也是属性}
    {事件命名一般用 On 开始}
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}


{ TMyClass }

constructor TMyClass.Create;
begin
  FOnHundred := SetOnHundred1; {在对象建立时, 我们先让事件调用 SetOnHundred1 方法}
end;

procedure TMyClass.SetAge(const Value: Integer);
begin
  if (Value>0) and (Value

抱歉!评论已关闭.