Enumeration from string

Given the following descriptions, is there a way to get an enum value (like jt_one) from a string value (like "one")?

type TJOBTYPEENUM =(jt_one, jt_two, jt_three); CONST JOBTYPEStrings : ARRAY [jt_one..jt_three] OF STRING = ('one','two','three'); 

Or do I need to create my own function using a nested set of if statements?

NOTE. I am not looking for the string "jt_one"

+4
source share
2 answers
 function EnumFromString(const str: string): TJOBTYPEENUM; begin for Result := low(Result) to high(Result) do if JOBTYPEStrings[Result]=str then exit; raise Exception.CreateFmt('Enum %s not found', [str]); end; 

In real code, you want to use your own exception class. And if you want to allow case insensitivity, compare strings using SameText .

+10
source
 function GetJobType(const S: string): TJOBTYPEENUM; var i: integer; begin for i := ord(low(TJOBTYPEENUM)) to ord(high(TJOBTYPEENUM)) do if JOBTYPEStrings[TJOBTYPEENUM(i)] = S then Exit(TJOBTYPEENUM(i)); raise Exception.CreateFmt('Invalid job type: %s', [S]); end; 

or, more accurately,

 function GetJobType(const S: string): TJOBTYPEENUM; var i: TJOBTYPEENUM; begin for i := low(TJOBTYPEENUM) to high(TJOBTYPEENUM) do if JOBTYPEStrings[i] = S then Exit(i); raise Exception.CreateFmt('Invalid job type: %s', [S]); end; 
+7
source

Source: https://habr.com/ru/post/1440614/


All Articles