首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 屬性機制深度解析:欄位封裝、存取方法與資料驗證實務

     編輯:Delphi

欄位 vs 屬性:核心差異

欄位是類別內部的資料儲存單元;屬性是對外公開的存取介面,可攔截讀寫操作,注入驗證邏輯。

對比範例:無屬性 vs 有屬性

TMyClass1:公開欄位,零保護


TMyClass1 = class
  FName: string; // 命名慣例:F 開頭
  FAge: Integer;
end;

外部可任意寫入:`Obj.FAge := 1000`(不合理數值)。

TMyClass2:封裝欄位 + 屬性存取


TMyClass2 = class
strict private
  FName: string;
  FAge: Integer;
  procedure SetAge(const Value: Integer);
  procedure SetName(const Value: string);
published
  property Name: string read FName write SetName;
  property Age: Integer read FAge write SetAge;
end;

屬性三要素

要素說明範例
資料型別屬性對外呈現的型別property Age: Integer
讀取規則read 指定欄位或函數read FAge(直接讀欄位)
寫入規則write 指定欄位或程序write SetAge(呼叫驗證方法)

存取方法實作:資料驗證核心


procedure TMyClass2.SetAge(const Value: Integer);
begin
  if (Value >= 0) and (Value < 200) then
    FAge := Value; // 只接受合理年齡
end;

procedure TMyClass2.SetName(const Value: string);
begin
  if Value <> '' then
    FName := Value; // 拒絕空字串
end;

使用情境對比


var
  C1: TMyClass1;
  C2: TMyClass2;
begin
  C1 := TMyClass1.Create;
  C2 := TMyClass2.Create;

  C1.FAge := 1000; // 通過!資料受汙染
  C2.Age := 99;    // 通過,合理值
  // C2.Age := 1000; // 被 SetAge 攔截,FAge 不變
  // C2.FAge := 99;  // 編譯錯誤:strict private 不可見

  C1.Free; C2.Free;
end;

進階屬性功能

  • 索引屬性:property Items[Index: Integer]: String read GetItem write SetItem
  • 預設屬性:property Items[Index: Integer]: String read GetItem write SetItem; default
  • stored、default、nodefault:控制 DFM 序列化行為。
  • implements:介面代理(Delphi 2006+)。

總結

屬性是「資料的守門員」。善用 read/write 搭配存取方法,能在不改變外部呼叫語法的前提下,靈活加入驗證、快取、通知等邏輯,是 Delphi 封裝的核心工具。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved