How do I enumerate all properties in an object and obtain their values?

后端 未结 3 1740
醉酒成梦
醉酒成梦 2021-01-05 09:56

I want to enumerate all properties: private, protected, public etc. I wish to use the built in facilities and not use any third party code.

3条回答
  •  感情败类
    2021-01-05 10:08

    Use Extended RTTI like this (when I tested the code in XE I got exception on ComObject property, so I inserted 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;
    

提交回复
热议问题