How do I convert an integer to an enumerated type?

后端 未结 3 890
春和景丽
春和景丽 2020-12-30 23:35

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

type
  TMyType = (mtFirst, mtSecond, mtThird); 

var 
  ordValue:integer;
  enumValue:TMyType;
...
or         


        
相关标签:
3条回答
  • 2020-12-31 00:19

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

    ordValue := Ord(mtSecond);
    enumValue := TMyType(ordValue);
    
    0 讨论(0)
  • 2020-12-31 00:24

    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
    
    0 讨论(0)
  • 2020-12-31 00:37

    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');
    
    0 讨论(0)
提交回复
热议问题