Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate member variables

Is there a way to iterate the member variables of an object in D2010 without knowing what they are beforehand?

like image 288
John Zane Avatar asked Dec 17 '10 00:12

John Zane


1 Answers

Yes, if you're using Delphi 2010 or later. You can use extended RTTI to get information about an object's fields, methods and properties. Simple version:

procedure GetInfo(obj: TObject);
var
  context: TRttiContext;
  rType: TRttiType;
  field: TRttiField;
  method: TRttiMethod;
  prop: TRttiProperty;
begin
  context := TRttiContext.Create;
  rType := context.GetType(obj.ClassType);
  for field in rType.GetFields do
    ;//do something here
  for method in rType.GetMethods do
    ;//do something here
  for prop in rType.GetProperties do
    ;//do something here
end;

The necessary objects can be found in the RTTI unit.

In earlier versions of Delphi, there's some more limited RTTI that can get you some information about some properties and methods, but it can't do all that much.

like image 54
Mason Wheeler Avatar answered Oct 19 '22 09:10

Mason Wheeler