屬性是 Delphi 類封裝的核心語法糖,將字段讀寫封裝為統一介面,支援讀寫方法、索引、默認值、存儲控制、RTTI 等豐富特性。本文系統總結屬性定義規則、讀寫規範、訪問層級、事件屬性、數組屬性、默認屬性、類屬性等全維度知識。
TMyClass = class(TObject)
private
FName: string;
procedure SetName(const Value: string);
public
property Name: string read FName write SetName;
end;
property 定義,至少包含 read 或 write(單一則為只讀/只寫)。function GetName: string;)。const Value: string 或 Value: string)。virtual/dynamic/overload。published 區屬性的讀寫方法強制使用 register 約定。published(設計時可見、RTTI、流式存取),不需設計時可見可放 public 節省 RTTI 開銷。private,對外僅暴露屬性。property Name: string; 後按 Ctrl+Shift+C 自動補全讀寫方法聲明與實現骨架。property Items[Index: Integer]: string read GetItem write SetItem; default;
{default 使其成為默認屬性, 可 MyObj[5] 直接訪問}
property Value[Index: Integer]: Integer read GetValue write SetValue; {多屬性共用讀寫方法, 通過 Index 區分}
property Items[Index: Integer]: string read GetItem write SetItem; default;
{每類僅能有一個 default 屬性, 通常為數組屬性}
type
TMyClass = class
private
class var FCount: Integer;
class procedure SetCount(Value: Integer); static;
public
class property Count: Integer read FCount write SetCount;
end;
property Name: string read FName write SetName stored False; {不序列化}
property Name: string read FName write SetName stored IsNameStored; {動態決定}
property Name: string read FName write SetName default 'DefaultName'; {默認值, 不存儲默認值}
property Name: string read FName write SetName implements IInterface; {介面代理實現}
| 錯誤代碼 | 問題 | 修正 |
|---|---|---|
property X: Integer read GetX write SetX;function GetX: Integer;procedure SetX(Value: Integer); virtual; | 寫方法為 virtual | 移除 virtual |
property Y: Integer read FY write FY;published | 直接讀寫字段但放 published | 移至 public 或改用方法 |
property Z: Integer read GetZ write SetZ; overload; | 屬性標記 overload | 屬性不支援 overload |
property A: Integer read GetA write SetA;function GetA: Integer; stdcall; | published 區方法用 stdcall | 移除 stdcall 或移至 public |
屬性是 Delphi 物件模型的靈魂,掌握其定義規範、讀寫簽名約束、訪問層級選擇、進階類型(數組/索引/默認/類/存儲/實現)與 IDE 輔助技巧,能編寫出封裝嚴密、設計時友好、運行高效的專業級類庫。