枚举类型没有基类型,就像 TObject 是类的基。
如果您有一个支持泛型的 Delphi 版本,您可以使用以下帮助器将泛型从序数值转换为枚举值。
uses
System.SysUtils,TypInfo;
Type
TEnumHelp<TEnum> = record
type
ETEnumHelpError = class(Exception);
class function Cast(const Value: Integer): TEnum; static;
end;
class function TEnumHelp<TEnum>.Cast(const Value: Integer): TEnum;
var
typeInf : PTypeInfo;
typeData : PTypeData;
begin
typeInf := PTypeInfo(TypeInfo(TEnum));
if (typeInf = nil) or (typeInf^.Kind <> tkEnumeration) then
raise ETEnumHelpError.Create('Not an enumeration type');
typeData := GetTypeData(typeInf);
if (Value < typeData^.MinValue) then
raise ETEnumHelpError.CreateFmt('%d is below min value [%d]',[Value,typeData^.MinValue])
else
if (Value > typeData^.MaxValue) then
raise ETEnumHelpError.CreateFmt('%d is above max value [%d]',[Value,typeData^.MaxValue]);
case Sizeof(TEnum) of
1: pByte(@Result)^ := Value;
2: pWord(@Result)^ := Value;
4: pCardinal(@Result)^ := Value;
end;
end;
例子:
Type
TestEnum = (aA,bB,cC);
var
e : TestEnum;
...
e := TEnumHelp<TestEnum>.Cast(2); // e = cC
有一个限制:
不连续或不以零开头的枚举没有RTTI
TypeInfo 信息。见RTTI properties not returned for fixed enumerations: is it a bug?
。