理解Delphi的類(四)

來源:互聯網
上載者:User

先勾畫一下思路:

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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.