delphi rtti GetMethods 遍歷規則

del88發表於2024-08-01
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.JSON, system.Rtti;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    Button2: TButton;
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TPerson = class
  private
    FName: string;
    FAge: Integer;
    FSex: string;
  public
    property Name: string read FName write FName;
    property Age: Integer read FAge write FAge;
    property Sex: string read FSex write FSex;

    // 可以新增一些方法來測試 RTTI 遍歷
    procedure SayHello;
    function GetFullName: string;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TPerson.SayHello;
begin
  WriteLn('Hello, my name is ' + FName);
end;

function TPerson.GetFullName: string;
begin
  Result := FName + ' (' + FSex + ', ' + IntToStr(FAge) + ' years old)';
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  Context: TRttiContext;
  RttiType: TRttiType;
  Method: TRttiMethod;
begin
  try
    Context := TRttiContext.Create;
    try
      RttiType := Context.GetType(TPerson);
      for Method in RttiType.GetMethods do
      begin
        Memo1.Lines.Add('Method: ' + Method.Name);
        // 這裡可以進一步處理每個方法,比如呼叫它
      end;
    finally
      Context.Free;
    end;
  except
    on E: Exception do
      WriteLn(E.ClassName, ': ', E.Message);
  end;
end;

end.

image

我們通常都是希望從子類裡找到某一個方法,他優先子類這樣效率就高些;

在開發中,儘量使用 RttiType.GetMethods 一次性找出 你需要的方法,而不是透過 RttiType.GetMethod('SayHello'); 逐個去獲取,

因為 逐個獲取 每一個方法 他內部都得遍歷一次,不如直接遍歷一次 得到所有 效率高;

相關文章