对于普通的枚举,我可以循环访问并获取所有名称:
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);
答案 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;