2011-12-30 10 views
6

Quiero enumerar todas las propiedades: privado, protegido, público, etc. Deseo utilizar las instalaciones integradas y no utilizar ningún código de terceros.¿Cómo enumero todas las propiedades en un objeto y obtengo sus valores?

+0

¿Con qué versión de Delphi estás trabajando? El RTTI mejorado solo está disponible desde Delphi 2010. Las versiones anteriores no podrán lograrlo: solo se pueden enumerar las propiedades publicadas. –

+1

Usted está preguntando sobre obtener los valores de todas las propiedades. El nuevo RTTI, disponible en Delphi XE2, puede hacer esto. El enlace que publiqué como duplicado fue una referencia sobre el uso de RTTI, en general. No había ninguna indicación de la versión de Delphi que estabas usando. Desde que editó su pregunta, eliminé mi duplicado. –

+1

@DavidHeffernan, gracias por modificar mis preguntas muy bien. – VibeeshanRC

Respuesta

5

Uso RTTI extendido como esto (cuando probé el código en XE llegué excepción en la propiedad ComObject, por lo que he insertado intento - a excepción de bloque):

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

respuesta de Serg es bueno, pero es mejor evitar excepciones por saltarse algunos tipos:

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

Aquí es un excelente punto de partida utilizando las capacidades avanzadas de la reciente versión de Delphi:

El siguiente enlace se dirige más bien a la versión anterior (de D5 en adelante). Sobre la base de los TypInfo.pas unidad, es limitado, pero todavía instructiva:

Cuestiones relacionadas