Skip to content

Instantly share code, notes, and snippets.

@johnidm
Created February 12, 2014 11:27
Show Gist options
  • Save johnidm/8953836 to your computer and use it in GitHub Desktop.
Save johnidm/8953836 to your computer and use it in GitHub Desktop.
Implements a read of enum with description generic in Delphi
type
TEnumConv = record
class function GetList<TEnum>( const AArray: array of string ): TStringList; static;
end;
class function TEnumConv.GetList<TEnum>( const AArray: array of string ): TStringList;
var
TypeInf: Pointer;
Index: Integer;
Name: string;
begin
if PTypeInfo(TypeInfo(TEnum))^.Kind <> tkEnumeration then
raise EInvalidCast.Create('Invalid class type');
Result:= TStringList.Create();
for Index:= Low( AArray ) to High( AArray ) do
begin
TypeInf:= TypeInfo(TEnum);
Name:= GetEnumName( TypeInf , Index);
Result.Add( IntToStr( GetEnumValue( TypeInfo(TEnum), Name ) )+ '=' + AArray[ Index ] );
end;
end;
type
TProgrammer = (tpDelphi, tpRuby, tpJava );
TCountries = ( ctrBrasil, ctrArgentina, ctrUruguai, ctrParaguai, ctrChile );
const
PROGRAMER_DESC: array[ TProgrammer ] of string = ( 'Delphi', 'Ruby', 'Java' );
COUNTRIES_DESC: array[ TCountries ] of string = ( 'Brasil', 'Argentina', 'Uruguai', 'Paraguai', 'Chile' );
var
List: TStringList;
begin
List:= TEnumConv.GetList<TProgrammer>( PROGRAMER_DESC );
try
CheckEqualsString( '0=Delphi' , List[0] );
CheckEqualsString( '1=Ruby' , List[1] );
CheckEqualsString( '2=Java' , List[2] );
finally
FreeAndNil( List )
end;
var
List: TStringList;
begin
List:= TEnumConv.GetList<TCountries>( COUNTRIES_DESC );
try
CheckEqualsString( '0=Brasil' , List[0] );
CheckEqualsString( '1=Argentina' , List[1] );
CheckEqualsString( '2=Uruguai' , List[2] );
CheckEqualsString( '3=Paraguai' , List[3] );
CheckEqualsString( '4=Chile' , List[4] );
finally
FreeAndNil( List )
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment