How to convert an enumeration value to a string?

I know that I managed to do this before, so it should be possible.

I would like to convert an element, such as the alignment property of the alNone component, into a string that I can save, display anything. I know that I can get the byte value and come up with my own text, but I'm sure there is a more direct way.

For example, I want ...

var S:string; S:= somehow(Form.Align); ShowMessage(S); 

where "somehow", however, I convert the parameter for the form alignment property to a string, such as "alNone".

+6
source share
2 answers

Form.Align not a TPersistent value. This is the TAlign value, which is an enumeration type.

You can convert the enumeration value to a string using this piece of code:

 type TEnumConverter = class public class function EnumToInt<T>(const EnumValue: T): Integer; class function EnumToString<T>(EnumValue: T): string; end; class function TEnumConverter.EnumToInt<T>(const EnumValue: T): Integer; begin Result := 0; Move(EnumValue, Result, sizeOf(EnumValue)); end; class function TEnumConverter.EnumToString<T>(EnumValue: T): string; begin Result := GetEnumName(TypeInfo(T), EnumToInt(EnumValue)); end; 

You need to add System.TypInfo to use.

Do this to get Form.Align as a string:

 S := TEnumConverter.EnumToString(Form.Align) 
+6
source

You can do this with RTTI:

 uses RTTI; procedure TForm40.FormCreate(Sender: TObject); var sAlign: string; eAlign: TAlign; begin //Enum to string sAlign := TRttiEnumerationType.GetName(Align); //string to enum eAlign := TRttiEnumerationType.GetValue<TAlign>(sAlign); end; 
+6
source

All Articles