2011-12-30 21 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單位,它是有限的,但仍具有啓發性: