2011-12-30 65 views
6

我想枚举所有属性:私人,保护,公共等我希望使用内置的设施,不使用任何第三方代码。如何枚举对象中的所有属性并获取其值?

+0

您正在使用哪个版本的Delphi?增强RTTI仅在德尔福2010年以后才可用。旧版本将无法实现此目的:只能列出发布的属性。 – 2011-12-30 13:10:32

+1

您正在询问获取所有房产的价值。 Delphi XE2提供的新RTTI可以做到这一点。我发布的重复链接是关于使用RTTI的一些参考资料。没有迹象表明你正在使用的Delphi版本。既然你编辑了你的问题,我删除了我的副本。 – 2011-12-30 13:57:31

+1

@DavidHeffernan,谢谢你很好地修改我的问题。 – VibeeshanRC 2011-12-30 14:06:50

回答

5

使用扩展RTTI这样的(当我测试了XE的代码我得到异常的ComObject财产,所以我插入的尝试 - 除了块):

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; 
7

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; 
2

下面是使用的最新版本的Delphi高级功能的最佳出发点:

下面的链接,而不是目标早期版本(从D5开始)。基于TypInfo.pas单位,它是有限的,但仍具有启发性: