1

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;
Robatron
  • 83
  • 9
  • 2
    https://stackoverflow.com/q/31601707/62576 should give you a place to start. You have a couple of problems already in your pseudocode. First, you can't create an instance of `tStrings`, as it's an abstract type. You have to use one of its descendants such as `TStringList`. Second, there is no version of `TStrings.Add` that accepts two arguments such as you've used. Third, `GetEnumName` requires a value from which to return the name as an argument. Also, it's a bad idea to have a function return an object it creates, as it's unclear who manages the memory. Pass a stringlist into the function. – Ken White Dec 30 '20 at 01:23
  • Also, `length(enum)` needs to be `length(enum) - 1`. – Andreas Rejbrand Dec 30 '20 at 11:19
  • Yeah, I see my pseudo code wasn’t really well defined. Updating.... – Robatron Jan 01 '21 at 20:04

1 Answers1

3

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

Para
  • 1,299
  • 4
  • 11