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'); 逐个去获取,

因为 逐个获取 每一个方法 他内部都得遍历一次,不如直接遍历一次 得到所有 效率高;

posted on 2024-08-01 07:38  del88  阅读(9)  评论(0编辑  收藏  举报