Search code examples
delphivariablesdelphi-2010memberloops

Iterate member variables


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


Solution

  • 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.