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

深入理解 Delphi 類(十二):屬性全方位解析與最佳實踐

     編輯:Delphi

前言

屬性是 Delphi 類封裝的核心語法糖,將字段讀寫封裝為統一介面,支援讀寫方法、索引、默認值、存儲控制、RTTI 等豐富特性。本文系統總結屬性定義規則、讀寫規範、訪問層級、事件屬性、數組屬性、默認屬性、類屬性等全維度知識。

標準屬性定義範本

TMyClass = class(TObject)
private
  FName: string;
  procedure SetName(const Value: string);
public
  property Name: string read FName write SetName;
end;

12 條核心規範

  1. 關鍵字:property 定義,至少包含 read 或 write(單一則為只讀/只寫)。
  2. 類型聲明:屬性名後必須指定類型(內置或前向聲明類型),讀寫目標類型必須一致。
  3. 前置聲明:讀寫使用的字段/方法必須在屬性定義之前聲明。
  4. 讀方法簽名:無參數函數,返回類型與屬性一致(如 function GetName: string;)。
  5. 寫方法簽名:單參數過程,參數類型與屬性一致,必須傳值(const Value: string 或 Value: string)。
  6. 不可為虛/動態/重載:屬性讀寫方法不能是 virtual/dynamic/overload。
  7. 調用約定:published 區屬性的讀寫方法強制使用 register 約定。
  8. 訪問層級:屬性通常放 published(設計時可見、RTTI、流式存取),不需設計時可見可放 public 節省 RTTI 開銷。
  9. 封裝性:底層字段/方法放 private,對外僅暴露屬性。
  10. 事件屬性:讀寫必須為方法指針類型,不能直接用字段。
  11. 本質:屬性無獨立內存/指針,僅是訪問字段/方法的語法橋樑,編譯期展開為方法調用或直接字段偏移。
  12. IDE 輔助:輸入 property Name: string; 後按 Ctrl+Shift+C 自動補全讀寫方法聲明與實現骨架。

進階屬性類型

1. 數組屬性

property Items[Index: Integer]: string read GetItem write SetItem; default;
{default 使其成為默認屬性, 可 MyObj[5] 直接訪問}

2. 索引屬性

property Value[Index: Integer]: Integer read GetValue write SetValue; {多屬性共用讀寫方法, 通過 Index 區分}

3. 默認屬性

property Items[Index: Integer]: string read GetItem write SetItem; default;
{每類僅能有一個 default 屬性, 通常為數組屬性}

4. 類屬性

type
  TMyClass = class
  private
    class var FCount: Integer;
    class procedure SetCount(Value: Integer); static;
  public
    class property Count: Integer read FCount write SetCount;
  end;

5. 存儲控制

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'; {默認值, 不存儲默認值}

6. 實現指令

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 輔助技巧,能編寫出封裝嚴密、設計時友好、運行高效的專業級類庫。

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