2010. október 24., vasárnap

Convert a string to a set and vice versa using RTTI

Problem/Question/Abstract:

Given a string like '[mbOk, mbCancel]', what is a simple way to use the routines in TypInfo to produce the corresponding set?

Answer:

uses
TypInfo;

function ButtonStringToSet(const S: string): TMsgDlgButtons;
var
Temp: TStringlist;
I: Integer;
N1, N2: Integer;
begin
Result := [];
N1 := Pos('[', S);
N2 := Pos(']', S);
if N2 = 0 then
N2 := Length(S) + 1;
Assert(N2 > N1);
Temp := TStringlist.Create;
try
Temp.Commatext := Copy(S, N1 + 1, N2 - N1 - 1);
for i := 0 to Temp.Count - 1 do
Include(Result, TMsgDlgBtn(TypInfo.GetEnumValue(TypeInfo(TMsgDlgBtn),
Trim(Temp[I]))));
finally
Temp.Free;
end;
end;

function SetToButtonString(Buttons: TMsgDlgButtons): string;
var
Temp: TStringlist;
Btn: TMsgDlgBtn;
begin
Temp := TStringlist.Create;
try
for Btn := Low(Btn) to High(Btn) do
if Btn in Buttons then
Temp.Add(TypInfo.GetEnumName(TypeInfo(TMsgDlgBtn), Ord(Btn)));
Result := Format('[%s]', [Temp.Commatext]);
finally
Temp.Free;
end;
end;


Nincsenek megjegyzések:

Megjegyzés küldése