开发者

Enumerations in Delphi with custom values

开发者 https://www.devze.com 2023-01-14 18:48 出处:网络
It is possible to de开发者_运维技巧clare enums with custom values in Delphi 5 like this?: type MyEnum = (meVal1 = 1, meVal2 = 3); // compiler error

It is possible to de开发者_运维技巧clare enums with custom values in Delphi 5 like this?:

type
  MyEnum = (meVal1 = 1, meVal2 = 3); // compiler error

Thanks!


In older Delphis you can do

type
  MyEnum = (meUnused1, meVal1, meUnused2, meVal2);


This is legal according to this article. I do recall that in early versions of Delphi supplying values wasn't supported.

It might help to provide the 'compiler error' you received. Also, what version of Delphi are you using?


If you have an older version of Delphi (<= D5 IIRC) you can't do this. Maybe you can replace the enum by constants? Something like

const
  meVal1 = 1;
  meVal2 = 3;

type
  TMyEnum = Byte; // or Integer or ... - depends on your needs.

Unfortunately, the compiler can't do as much error checking for you with this as with an enum type.


As a somewhat ugly extension to the answer by Ulrich you could do something like the following:

type
  TMyEnum = (meVal1, meVal2);

const
  MY_ENUM_VALS: array[TMyENum] of integer = (1, 3);

and access them as

if (aVal = MY_ENUM_VALS[meVal2]) then...

Not pretty, I grant you, but at least that way you get a little more compiler error checking for those earlier versions of Delphi.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号