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

后端 未结 3 1726
醉酒成梦
醉酒成梦 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:04

    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;
    

提交回复
热议问题