在Delphi中将枚举值转换为整数

时间:2017-03-29 10:45:40

标签: integer pascal enumeration delphi

是否可以在Delphi中将枚举值转换/转换为Integer?

如果是,那怎么样?

4 个答案:

答案 0 :(得分:16)

这是在documentation for enumerated types明确指出的:

若干预定义函数对序数值和类型标识符进行操作。其中最重要的概述如下。

| Function |                       Parameter                       |                      Return value | Remarks                                           |
|----------|:-----------------------------------------------------:|----------------------------------:|---------------------------------------------------|
| Ord      |                   Ordinal expression                  |  Ordinality of expression's value | Does not take Int64 arguments.                    |
| Pred     |                   Ordinal expression                  | Predecessor of expression's value |                                                   |
| Succ     |                   Ordinal expression                  |   Successor of expression's value |                                                   |
| High     | Ordinal type identifier or   variable of ordinal type | Highest value in type             | Also operates on short-string   types and arrays. |
| Low      | Ordinal type identifier or   variable of ordinal type | Lowest value in type              | Also operates on short-string   types and arrays. |

答案 1 :(得分:8)

在我写这篇文章的时候,我看到大卫给你发了一个很好的答案,但无论如何我都会发布:

program enums;
{$APPTYPE CONSOLE}
uses
  SysUtils, typinfo;
type
  TMyEnum = (One, Two, Three);
var
  MyEnum : TMyEnum;
begin
  MyEnum := Two;
  writeln(Ord(MyEnum));  // writes 1, because first element in enumeration is numbered zero

  MyEnum := TMyEnum(2);  // Use TMyEnum as if it were a function
  Writeln (GetEnumName(TypeInfo(TMyEnum), Ord(MyEnum)));  //  Use RTTI to return the enum value's name
  readln;
end.

答案 2 :(得分:4)

将枚举转换为整数是有效的。我无法评论其他答案,所以将此作为答案发布。转换为整数可能是一个坏主意(如果是,请评论)。

type
  TMyEnum = (zero, one, two);
var
  i: integer;
begin
  i := integer(two); // convert enum item to integer
  showmessage(inttostr(i));  // prints 2
end;

这可能类似于Ord(),但我不确定哪种是最佳做法。如果将枚举转换为整数

,上述方法也适用
type
  TMyEnum = (zero, one, two);
var
  MyEnum: TMyEnum;
  i: integer;
begin
  MyEnum := two; 
  i := integer(MyEnum);      // convert enum to integer
  showmessage(inttostr(i));  // prints 2
end;

答案 3 :(得分:0)

您可以使用Ord()函数。为清楚起见,编写一对IntToEnum()和EnumToInt()函数可能更好。