枚举(带有自定义值)到字符串/文本

Enumerations (with custom values) to String / Text

可以使用类似这样的方法将枚举转换为字符串:

uses
TypInfo;

type
  Language = (Delphi,Delphi_Prism,CBuilder);

var
  StrLanguage : String;
begin
  StrLanguage  := GetEnumName(TypeInfo(Language),integer(Delphi)) ; 
end;

(取自theroadtodelphi

是否可以对具有自定义值的枚举执行相同的操作?

像这样:

type
  THotkey = (hkShift= 1, hkSpace= 3, hkEnter= 6);

作为解决方法,我使用占位符来跳过未使用的枚举。

然而,如果我不得不跳过巨大的差距,这并不好,而且会有问题。

type
  THotkeys = (hkShift, hkUnused1, hkSpace, hkUnused2, hkUnused3, hkEnter);

答案就在你的例子中(如果我明白你在问什么)

type
  THotkeys = (hkShift, hkUnused1, hkSpace, hkUnused2, hkUnused3, hkEnter);

....

var
  StrLanguage : String;
begin
  StrLanguage  := GetEnumName(TypeInfo(THotkeys),integer(hkSpace)) ;
  ShowMessage(IntToStr(integer(hkSpace)) + ' - ' + StrLanguage);

结果将是:

2 - hkSpace

在您的特定用例中,您可以使用与枚举相关的数组,因为 具有特定值的枚举常量没有 RTTI,如 [=15] 中所述=]:

Enumerated constants without a specific value have RTTI:

type SomeEnum = (e1, e2, e3);

whereas enumerated constants with a specific value, such as the following, do not have RTTI:

type SomeEnum = (e1 = 1, e2 = 2, e3 = 3);

您可以像这样解决这个问题:

type
  THotkey = (hkShift, hkSpace, hkEnter);
  THotkeyValues: array[Thotkey] of Integer = (1,3,6);

用法:

ShiftKeyValue := THotkeyValues[hkShift];