views:

169

answers:

2

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.

+1  A: 

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.

Mason Wheeler
Yeah, I know. But I could swear that I have seen someone doing this using TValue. Thank you, anyway.
Fabricio Araujo
A: 

So you know how to do this:

function StrToEnumTest(aStr:String):TEnumTest;
begin
  result := TEnumTest(GetEnumValue(TypeInfo(TEnumTest),aStr));
end;

But you don't want to do it that way? Why? I wish we could do this:

inline function StrToEnumTest(aStr:String):<T>;
begin
  result := <T>(GetEnumValue(TypeInfo(<T>),aStr));
end;
Warren P
The angle brackets around the Ts only belong in the definition, not in the function body.
Mason Wheeler