简体   繁体   中英

Delphi Function to convert enum to string list…?

I'd like a function that takes an enum and returns a stringlist (or name:value pairs). It must be possible, the Object Inspector and Code Complete seem to do that. The pseudocode seems simple enough, but the details escape me....

function ParseEnum(e: Enum, S: TStringList): TStringList;
var
  i: Integer;
begin
  for i := 0 to length(enum) - 1 do
    S.Add(GetEnumName(e, i));
  Result := S;
end;

if this is a common funciton(all of Enum):
if the Enum is Continuity , as follows code is OK(by rtti)
if not Continuity i can't find a way now

type
TMyEnum = (s, b, c, d, e, f);


implementation
uses
  System.Rtti, TypInfo;

procedure ParseEnum<T>(sl: TStrings);
var
  rt: TRttiType;
  rot: TRttiOrdinalType;
  i: Integer;
begin
  rt := TRttiContext.Create.GetType(TypeInfo(T));
  rot := rt.AsOrdinal;
  for i := rot.MinValue to rot.MaxValue do
    sl.Add(GetEnumName(TypeInfo(T), i));
end;

procedure TForm1.btn1Click(Sender: TObject);
var
  sl: TStringList;
begin
  sl := TStringList.Create;
  try
    ParseEnum<TMyEnum>(sl);
    ShowMessage(sl.Text);
  finally
    sl.Free;
  end;
end;


why sl as a param but result: to attent people don't forget to free

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM