使用常量赋值遍历枚举类型并获取其名称

时间:2017-09-29 11:50:18

标签: delphi rtti

对于普通的枚举,我可以循环访问并获取所有名称:

type
  TMyEnum = (apple, pear, plum);

procedure TForm2.FormCreate(Sender: TObject);
var
  i: TMyEnum;
  s: String;
begin
  s:= '';
  for I := Low(TMyEnum) to High(TMyEnum) do
  begin
    s := s + TRttiEnumerationType.GetName<TMyEnum>(i) + sLineBreak;
  end;
  ShowMessage(s);
end;

但是,对于:

TMyEnum = (apple=5, pear=20, plum=70); 
  1. 如何迭代这个?
  2. 如何通过RTTI获取名称?

1 个答案:

答案 0 :(得分:2)

使用常量值声明的枚举类型不会获得RTTI,因此这种方式无法工作。根据您的要求,这可能是另一种选择:

type
  TMyEnum = (apple, pear, plum);

  TMyEnumHelper = record helper for TMyEnum
  private const
    cEnumInt: array[TMyEnum] of Integer = (5, 20, 70);
  public
    function GetAsInteger: Integer;
    procedure SetAsInteger(const Value: Integer);
    property AsInteger: Integer read GetAsInteger write SetAsInteger;
  end;

function TMyEnumHelper.GetAsInteger: Integer;
begin
  Result := cEnumInt[Self];
end;

procedure TMyEnumHelper.SetAsInteger(const Value: Integer);
var
  I: TMyEnum;
begin
  for I := Low(cEnumInt) to High(cEnumInt) do begin
    if cEnumInt[I] = Value then begin
      Self := I;
      Exit;
    end;
  end;
  raise ERangeError.Create('not a valid enum value');
end;