プロパティ値を文字列に変換/逆変換
|
published なプロパティを Ini に書き込みたい・から読み出したいというような時、プロパティ値を文字列に変換する必要が生じます。
Font プロパティを Ini/Registry に保存したい という投稿はFAQに近いですが、この記事はそういった要望への回答となります。
Enum/Set だけではなく、TColor のように「Enum ではないけど文字で書きこまれることがあるプロパティ」にも対応しています。
uses Classes, TypInfo;
function PropertyToString(obj: TPersistent; PropName: string): string;
var IntToIdent: TIntToIdent;
Ident: string;
begin
Result:= GetPropValue(obj, PropName);
if PropType(obj, PropName)=tkInteger then begin
IntToIdent := FindIntToIdent(GetPropInfo(obj, PropName).PropType^);
if Assigned(IntToIdent) then
IntToIdent(GetPropValue(obj, PropName), Result);
end;
end;
procedure StringToProperty(s: string; obj: TPersistent; PropName);
var IdentToInt: TIdentToInt;
i: Integer;
begin
if PropType(obj, PropName)==tkInteger then begin
IdentToInt:= FindIdentToInt(GetPropInfo(obj, PropName).PropType^);
if Assigned(IdentToInt) and IdentToInt(s, i) then begin
SetPropValue(obj, PropName, i);
end else begin
SetPropValue(obj, PropName, s);
end;
end else begin
SetPropValue(obj, PropName, s);
end;
end;
|
|