Главная » Delphi » Компоненты » Как получить значение property по его имени

Как получить значение property по его имени

12:41
unit Unit1;
 
interface
 
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, TypInfo;
 
type
  TForm1 = class(TForm)
    Label1: TLabel;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
 
implementation
 
{$R *.dfm}
 
function GetPropVal(Persistor: tPersistent;
  PropName: string): string;
var
  i: integer;
  propInfo: pPropInfo;
  Kinds: TTypeKinds;
  ClassProp: tObject;
begin
  Result := '';
  propinfo := getPropInfo(persistor, PropName, []);
  case propinfo^.proptype^.Kind of
    tkInteger:
      Result := intToStr(GetOrdProp(Persistor, PropInfo));
    tkChar:
      Result := char(GetOrdProp(Persistor, PropInfo));
    tkEnumeration:
      if PropInfo^.PropType^ = TypeInfo(boolean) then
        Result := GetEnumProp(Persistor, PropInfo)
      else
        Result := GetEnumProp(Persistor, PropInfo);
    tkFloat:
      if PropInfo^.PropType^ = TypeInfo(TDateTime) then
        Result := DateTimeToStr(GetFloatProp(Persistor, PropInfo))
      else
        if PropInfo^.PropType^ = TypeInfo(TTime) then
          Result := TimeToStr(GetFloatProp(Persistor, PropInfo))
        else
          if PropInfo^.PropType^ = TypeInfo(TDate) then
            Result := DateToStr(GetFloatProp(Persistor, PropInfo))
          else
            Result := FloatToStr(GetFloatProp(Persistor, PropInfo));
    tkString:
      Result := GetStrProp(Persistor, PropInfo);
    tkLString:
      Result := GetStrProp(Persistor, PropInfo);
    tkWString:
      Result := GetStrProp(Persistor, PropInfo);
    tkSet:
      Result := GetSetProp(Persistor, PropInfo);
    tkInt64:
      Result := intToStr(GetInt64Prop(Persistor, PropInfo));
    tkClass:
      begin
        ClassProp := GetObjectProp(Persistor, PropName);
        result := tPersistent(ClassProp).ClassName;
      end;
  end;
end;
 
procedure TForm1.Button1Click(Sender: TObject);
begin
  showmessage(GetPropVal(Label1, 'Caption'));
end;
 
end.