如何枚举对象中的所有属性并获取其值?

Vib*_*nRC 7 delphi delphi-xe2

我想枚举所有属性:私有,受保护,公共等.我希望使用内置设施而不使用任何第三方代码.

Lin*_*nas 9

Serg的答案很好,但最好通过跳过某些类型来避免异常:

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;
Run Code Online (Sandbox Code Playgroud)


klu*_*udg 6

像这样使用扩展RTTI(当我在XE中测试代码时,我在ComObject属性上得到了异常,所以我插入了try - except块):

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;
Run Code Online (Sandbox Code Playgroud)