您要求的是访问对象的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记录TRttiType和TRttiProperty类System.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)