delphidelphi-2010rttitvalue

Converting an string to a enum type using TValue?


I want to convert an string to an enum type using TValue, I googled but I didn't find how to do that.

type 
  TEnumTest = (etFirst, etSecond);

var 
  D: TEnumTest;
begin
  D := StrToENumTest('etFirst');
end;

function StrToEnumTest(pStr:String):TEnumTest;
var 
  V: TValue;
begin
  V := TValue.From<String>(pstr);
  Result := V.AsType<TEnumTest>;
end;

It doesn't work. That's must be something stupid I'm not seeing - but I didn't found it. What I made wrong?

I know how to use GetEnumValue.

EDIT: @Warren, it goes here as this is easier to post code:

  TEnumUtils = class
    class function GetAs<T>(pValor: String): T;
  end;

class function TEnumUtils.GetAs<T>(pValor: String): T;
var
  Tipo: PTypeInfo;
  Temp: Integer;
  PTemp: Pointer;

begin
   Tipo := TypeInfo(T);
   Temp := GetEnumValue(Tipo, pValor);
   PTemp := @Temp;
   Result := T(PTemp^);
end;

Usage:

type 
  TEnumTest = (etFirst, etSecond);

var 
  D: TEnumTest;
begin
  D := TEnumUtils.GetAs<TEnumTest>('etFirst');
end;  

Solution

  • What you're not seeing is the way TValue was designed. It's intended specifically as a way to contain values, not a way to convert them. If you want to convert between srtings and enums, as you said, you already know how. Use the functions provided for that purpose in TypeInfo.