Created
February 12, 2014 11:27
-
-
Save johnidm/8953836 to your computer and use it in GitHub Desktop.
Implements a read of enum with description generic in Delphi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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