从字符串const数组中检索字符串

Blo*_*mUp 0 delphi delphi-2010

如果我知道整数值的枚举,如何获得字符串表示?

type    
  MyEnum = (tmp_one, tmp_two, tmp_three);

const
  MyTypeNames: array[tmp_one..tmp_three] of string = ('One', 'Two', 'Three');
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 6

我假设你有一个序数值而不是这个枚举类型的变量.如果是这样,那么你只需要将序数强制转换为枚举类型.像这样:

function GetNameFromOrdinal(Ordinal: Integer): string;
begin
  Result := MyTypeNames[MyEnum(Ordinal)]; 
end;
Run Code Online (Sandbox Code Playgroud)

  • @Andreas我把它作为一个函数,因为这只是一个简单的方法来明确参数和返回值的类型 (3认同)

And*_*and 6

我假设你想在你的数组字符串中使用名称.然后这很简单:

var
  myEnumVar: MyEnum;
begin
  myEnumVar := tmp_two; // For example
  ShowMessage(MyTypeNames[myEnumVar]);
Run Code Online (Sandbox Code Playgroud)