Cast Enumeration Value to Integer in Delphi

拟墨画扇 提交于 2020-06-11 03:06:44

问题


Is it possible to cast/convert an Enumeration Value to Integer in Delphi?

If yes, then how?


回答1:


This is called out explicitly at the documentation for enumerated types:

Several predefined functions operate on ordinal values and type identifiers. The most important of them are summarized below.

| 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. |



回答2:


I see David has posted you a good answer while I was writing this, but I'll post it anyway:

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.



回答3:


Casting the enum to an integer works. I could not comment on the other answers so posting this as an answer. Casting to an integer may be a bad idea (please comment if it is).

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

Which may be similar to Ord(), but I am unsure which is the best practice. The above also works if you cast the enum to an integer

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;



回答4:


You can use the Ord() function for this. For clarity it may be better to write a pair of IntToEnum() and EnumToInt() functions though.



来源:https://stackoverflow.com/questions/43091323/cast-enumeration-value-to-integer-in-delphi

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