How to list all the properties of an object and get their values?

I want to list all the properties: private, protected, public, etc. I want to use the built-in tools and not use third-party code.

+6
source share
3 answers

Use Extended RTTI like this (when I tested the code in XE, I got an exception in the ComObject property, so I inserted a try-except block):

uses RTTI; procedure TForm1.Button1Click(Sender: TObject); var C: TRttiContext; T: TRttiType; F: TRttiField; P: TRttiProperty; S: string; begin T:= C.GetType(TButton); Memo1.Lines.Add('---- Fields -----'); for F in T.GetFields do begin S:= F.ToString + ' : ' + F.GetValue(Button1).ToString; Memo1.Lines.Add(S); end; Memo1.Lines.Add('---- Properties -----'); for P in T.GetProperties do begin try S:= P.ToString; S:= S + ' : ' + P.GetValue(Button1).ToString; Memo1.Lines.Add(S); except ShowMessage(S); end; end; end; 
+5
source

Serg's answer is good, but it is better to avoid exceptions by skipping some types:

 uses Rtti, TypInfo; procedure TForm4.GetObjectProperties(AObject: TObject; AList: TStrings); var ctx: TRttiContext; rType: TRttiType; rProp: TRttiProperty; AValue: TValue; sVal: string; const SKIP_PROP_TYPES = [tkUnknown, tkInterface]; begin if not Assigned(AObject) and not Assigned(AList) then Exit; ctx := TRttiContext.Create; rType := ctx.GetType(AObject.ClassInfo); for rProp in rType.GetProperties do begin if (rProp.IsReadable) and not (rProp.PropertyType.TypeKind in SKIP_PROP_TYPES) then begin AValue := rProp.GetValue(AObject); if AValue.IsEmpty then begin sVal := 'nil'; end else begin if AValue.Kind in [tkUString, tkString, tkWString, tkChar, tkWChar] then sVal := QuotedStr(AValue.ToString) else sVal := AValue.ToString; end; AList.Add(rProp.Name + '=' + sVal); end; end; end; 
+7
source

Here's a great starting point using the advanced features of the latest Delphi version:

The following link rather targets the earlier version (with D5 on). Based on the TypInfo.pas module, it is limited but still instructive:

+2
source

Source: https://habr.com/ru/post/904749/


All Articles