Ver Mensaje Individual
  #1  
Antiguo 27-07-2012
elarys elarys is offline
Miembro
 
Registrado: abr 2007
Posts: 94
Reputación: 18
elarys Va por buen camino
Tipo de Propiedades y valor de una clase u objeto TypInfo

En realidad no se si estoy haciendo correctamente la pregunta

Aqui mi unidad, solo un formulario (Form1) y un boton (btnPrueba)
Código Delphi [-]
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics,
  Controls, Forms, Dialogs, StdCtrls, ComCtrls, TypInfo;

type
  TProducto = Class(TPersistent)
  private
    FCodigo:integer;
    FNuevos:boolean;
    FNombre:string;
    FPrecio:double;
    FCreado:TDateTime;
    FClaves:TStringList;
  public

  published
    property Codigo: integer read FCodigo write FCodigo;
    property Nuevos: boolean read FNuevos write FNuevos;
    property Nombre: string read FNombre write FNombre;
    property Precio: double read FPrecio write FPrecio;
    property Creado: TDateTime read FCreado write FCreado;
    property Claves: TStringList read FClaves write FClaves;

    Constructor Create;
  end;

  TForm1 = class(TForm)
    btnPrueba: TButton;
    procedure btnPruebaClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    Producto:TProducto;
    procedure GetPropertyList(Obj: TObject; List: TStrings; Filter: TTypeKinds);
  public

  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

Constructor TProducto.Create;
begin
  FClaves := TStringList.Create;
end;

procedure TForm1.btnPruebaClick(Sender: TObject);
var
  Value, Tipo: string;
  Lista: TStringList;
  i: Integer;
  XMLFile: TextFile;
  PInfo: PPropInfo;
begin
  Lista := TStringList.Create;

  GetPropertyList(Producto, Lista, tkProperties);

  AssignFile(XMLFile, ExtractFilePath(Application.ExeName) + 'prueba.xml');
  Rewrite(XMLFile);
  WriteLn(XMLFile, '');

  for i := 0 to Lista.Count - 1 do
  begin
    Value := GetPropValue(Producto, Lista[i]);
    PInfo := GetPropInfo(Producto, Lista[i]);
    if PInfo <> nil then
    begin
      case PInfo^.PropType^.Kind of
        tkUnknown: Tipo := 'Unknown';
        tkInteger: Tipo := 'Integer';
        tkChar: Tipo := 'Char';
        tkEnumeration: Tipo := 'Enumeration';
        tkFloat: Tipo := 'Float';
        tkString: Tipo := 'String';
        tkSet: Tipo := 'Set';
        tkClass: Tipo := 'Class';
        tkMethod: Tipo := 'Method';
        tkWChar: Tipo := 'WChar';
        tkLString: Tipo := 'LString';
        tkWString: Tipo := 'WString';
        tkVariant: Tipo := 'Variant';
        tkArray: Tipo := 'Array';
        tkRecord: Tipo := 'Record';
        tkInterface: Tipo := 'Interface';
        tkInt64: Tipo := 'Int64';
        tkDynArray: Tipo := 'DynArray';
      end;
    end;

    WriteLn(XMLFile, '  <' + UpperCase(Lista[i]) + '>' + Value + ' + UpperCase(Lista[i]) + '>');
  end;
  WriteLn(XMLFile, '');
  CloseFile(XMLFile);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Producto := TProducto.Create;
  Producto.Codigo := 100;
  Producto.Nuevos := True;
  Producto.Nombre := 'Notebook HP';
  Producto.Precio := 3599.99;
  Producto.Creado := Date;
  Producto.Claves.Add('Codigo');
  Producto.Claves.Add('Lugar');
end;

procedure TForm1.GetPropertyList(Obj: TObject; List: TStrings; Filter: TTypeKinds);
var
  PropList: PPropList;
  Count,i: integer;
begin
  List.Clear;
  Count := GetPropList(Obj.ClassInfo, Filter, nil);
  GetMem(PropList, Count * SizeOf(PPropInfo));
  GetPropList(Obj.ClassInfo, Filter, PropList);

  for i := 0 to Count -1 do
    List.Add(Proplist[i].Name);
end;

end.

Apartir de la clase Producto = Class(TPersistent)
Donde estan definidos sus tipos, quiero por medio de TypInfo o RTTI
Obtener las propiedades y sus respectivos valores.
Vale aclarar que la clase Producto es mucho mas extensa y esta definida en otra unidad, aqui esta resumida para el caso practico.

Con el procedimiento GetPropertyList(Producto, Lista, tkProperties);
Obtengo la lista de propiedades de Producto y se carga en Lista: TStringList
Luego recorriendo ese TStringList obtengo cada uno de los valores y su tipo
Value := GetPropValue(Producto, Lista[i]);
PInfo := GetPropInfo(Producto, Lista[i]);

Mi problema es que al ver los valores siguientes
FCreado:TDateTime;
FClaves:TStringList;
Estos me devuelven numeros de tipo float
Supongamos que en el caso del TDateTime esto sea correcto porque se maneja asi...
Como hago para que eso que me devuelve lo pase a fecha (dd/mm/yyyy) que el usuario ve, siendo que el tipo devuelto es un tkfloat, el usuario no entiende ese numero float, yo tengo que mostrarle la fecha.

En el caso de claves es mas complicado porque lo que me devuelve tambien es un numero float, pero el tipo es un tkClass, como hago para sacar los valores que tiene ese stringlist

Lo que pensaba era, volver a la funcion, donde le paso la clase producto apuntando a claves que es lo que quiero que me devuelva ahora... pero la lista la deja vacia, como que no encuentra ese elemento
GetPropertyList(Producto.Claves, Lista2, tkProperties);

Tambien probe con este procedimiento, tambien me devuelve la lista vacia

GetPropertyNames(Producto.Claves, Lista);
Código Delphi [-]
procedure TForm1.GetPropertyNames(Obj: TObject; var PropertyNames: TStringList);
var
  TypeInfo: PTypeInfo;
  TypeData: PTypeData;
  PropList: PPropList;
  i: Integer;
begin
  if Assigned(PropertyNames) then
  begin
    PropertyNames.Clear;
    TypeInfo := Obj.ClassInfo;
    if TypeInfo^.Kind = tkClass then
    begin
      TypeData := GetTypeData(TypeInfo);

      if TypeData^.PropCount > 0 then
      begin
        PropertyNames.Add(TypeInfo^.Name+':');
        new(PropList);
        GetPropInfos(TypeInfo, PropList);
        for i:=0 to Pred(TypeData^.PropCount) do
          if PropertyNames.IndexOf(PropList^[i]^.Name) < 0 then
            PropertyNames.Add(PropList^[i]^.Name);
          Dispose(PropList)
      end;
    end;
  end;
end;
Responder Con Cita