简体   繁体   中英

How can I get an enumeration's valid ranges using RTTI or TypeInfo in Delphi

I am using RTTI in a test project to evaluate enumeration values, most commonly properties on an object. If an enumeration is out of range I want to display text similar to what Evaluate/Modify IDE Window would show. Something like "(out of bound) 255".

The sample code below uses TypeInfo to display the problem with a value outside the enumeration as an Access Violation when using GetEnumName . Any solution using RTTI or TypeInfo would help me, I just don't know the enumerated type in my test code

program Project60;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,  TypInfo;

Type
  TestEnum = (TestEnumA, TestEnumB, TestEnumC);

const
  TestEnumUndefined = TestEnum(-1);

  procedure WriteEnum(const ATypeInfo: PTypeInfo; const AOrdinal: Integer);
  begin
    WriteLn(Format('Ordinal: %d = "%s"', [AOrdinal, GetEnumName(ATypeInfo, AOrdinal)]));
  end;


var
  TestEnumTypeInfo: PTypeInfo;
begin

  try
    TestEnumTypeInfo := TypeInfo(TestEnum);

    WriteEnum(TestEnumTypeInfo, Ord(TestEnumA));
    WriteEnum(TestEnumTypeInfo, Ord(TestEnumB));
    WriteEnum(TestEnumTypeInfo, Ord(TestEnumC));
    WriteEnum(TestEnumTypeInfo,  Ord(TestEnumUndefined));   //AV

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  ReadLn;
end.

Use GetTypeData() to get more detailed information from a PTypeInfo , eg:

procedure WriteEnum(const ATypeInfo: PTypeInfo; const AOrdinal: Integer);
var
  LTypeData: PTypeData;
begin
  LTypeData := GetTypeData(ATypeInfo);
  if (AOrdinal >= LTypeData.MinValue) and (AOrdinal <= LTypeData.MaxValue) then
    WriteLn(Format('Ordinal: %d = "%s"', [AOrdinal, GetEnumName(ATypeInfo, AOrdinal)]))
  else
    WriteLn(Format('Ordinal: %d (out of bound)', [AOrdinal]));
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM