对象的属性列表

use*_*405 3 delphi

如何获取不是Component的Object的属性列表(在运行时).就像Grid Cell一样,它有自己的属性(Font,Align等).

网格如AdvStringGrid或AliGrid,或Bergs NxGrid.

Rem*_*eau 8

您要求的是访问对象的RTTI(运行时类型信息).

如果您使用的是Delphi 2009或更早版本,则RTTI仅公开已发布的属性和已发布的方法(即事件处理程序).查看单元中的GetPropInfos()GetPropList()功能System.TypInfo.它们为您提供了一系列TPropInfo记录指针,每个属性一个.TPropInfo有一个Name成员(除其他外).

uses
  TypInfo;

var
  PropList: PPropList;
  PropCount, I: Integer;
begin
  PropCount := GetPropList(SomeObject, PropList);
  try
    for I := 0 to PropCount-1 do
    begin
      // use PropList[I]^ as needed...
      ShowMessage(PropList[I].Name);
    end;
  finally
    FreeMem(PropList);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

请注意,这种RTTI仅适用于派生自TPersistent{M+}应用了编译器指令的类(TPersistent确实如此).

如果您使用的是Delphi 2010或更高版本,则无论其可见性如何,扩展 RTTI都会公开所有属性,方法和数据成员.查看单元中的TRttiContext记录TRttiTypeTRttiPropertySystem.Rtti.有关更多详细信息,请参阅Embarcadero的文档:使用RTTI.

uses
  System.Rtti;

var
  Ctx: TRttiContext;
  Typ: TRttiType;
  Prop: TRttiProperty;
begin
  Typ := Ctx.GetType(SomeObject.ClassType);
  for Prop in Typ.GetProperties do
  begin
    // use Prop as needed...
    ShowMessage(Prop.Name);
  end;
  for Prop in Typ.GetIndexedProperties do
  begin
    // use Prop as needed...
    ShowMessage(Prop.Name);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

  • 没有理由创建TRttiContext.当你开始使用它时我会初始化它 (2认同)