先勾畫一下思路:
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<200) then
Fage := Value;
if Value=100 then
OnHundred; {當輸入的年齡是 100 歲時, 啟用事件}
end;
procedure TMyClass.SetOnHundred1;
begin
ShowMessage('祝賀您 100 歲大壽!');
end;
procedure TMyClass.SetOnHundred2;
begin
ShowMessage('但願我們都能活到 100 歲!');
end;