delphi - how to get type of enum

℡╲_俬逩灬. 提交于 2019-12-06 13:39:48
LU RD

There is no such thing as a base type for an enumeration type, like TObject is the base for classes.

If you have a Delphi version that supports generics, you can use following helper to make a generic cast from an ordinal value to an enumeration value.

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;

Example:

Type
  TestEnum = (aA,bB,cC);

var
  e : TestEnum;
...
e := TEnumHelp<TestEnum>.Cast(2);  // e = cC

There is one limitation:

Enumerations that are discontiguous or does not start with zero, have no RTTI TypeInfo information. See RTTI properties not returned for fixed enumerations: is it a bug?.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!