Blo*_*mUp 5 delphi delphi-2010
鉴于下面的声明如下,有没有办法从字符串值(例如'one')中检索枚举值(例如jt_one)?
type
TJOBTYPEENUM =(jt_one, jt_two, jt_three);
CONST JOBTYPEStrings : ARRAY [jt_one..jt_three] OF STRING =
('one','two','three');
Run Code Online (Sandbox Code Playgroud)
或者我是否需要使用嵌套的if语句创建自己的函数?
注意:我不是在寻找字符串"jt_one"
Dav*_*nan 10
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;
Run Code Online (Sandbox Code Playgroud)
在实际代码中,您需要使用自己的异常类.如果您想允许不区分大小写的匹配,请使用比较字符串SameText.
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;
Run Code Online (Sandbox Code Playgroud)
或者,整洁,
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3208 次 |
| 最近记录: |