How do I convert an integer to an enumerated type?

倖福魔咒の 提交于 2019-11-29 10:59:13

问题


I know how to convert an enumerated type to an integer.

type
  TMyType = (mtFirst, mtSecond, mtThird); 

var 
  ordValue:integer;
  enumValue:TMyType;
...
ordValue:= Ord(mtSecond); // result is 1

But how do I do the inverse operation and convert an integer to an enumerated type?


回答1:


As Ken answered, you just cast it. But to make sure you have correct value you can use code like:

if (ordValue >= Ord(Low(TMyType))) and (ordValue <= Ord(High(TMyType))) then
    enunValue := TMyType(ordValue)
else 
    raise Exception.Create('ordValue out of TMyType range');



回答2:


You can cast the integer by typecasting it to the enumerated type:

ordValue := Ord(mtSecond);
enumValue := TMyType(ordValue);



回答3:


Take care with casting because it requires full mapping with your ordinal type and integers. For example:

type Size = (Small = 2, Medium = 3, Huge = 10);
var sz: Size;
...
sz := Size(3); //means sz=Medium
sz := Size(7); //7 is in range but gives sz=outbound


来源:https://stackoverflow.com/questions/8732391/how-do-i-convert-an-integer-to-an-enumerated-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!