如何在Delphi中使用RTTI或TypeInfo获取枚举的有效范围 [英] How can I get an enumeration's valid ranges using RTTI or TypeInfo in Delphi

查看:82
本文介绍了如何在Delphi中使用RTTI或TypeInfo获取枚举的有效范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在测试项目中使用RTTI来评估枚举值,最常见的是对象的属性.如果枚举超出范围,我想显示类似于评估/修改IDE窗口"显示的文本.类似于((超出范围)255").

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".

下面的示例代码使用TypeInfo在使用 GetEnumName 时将枚举值以外的值显示为访问冲突问题.任何使用RTTI或TypeInfo的解决方案都会对我有所帮助,我只是不知道测试代码中的枚举类型

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.

推荐答案

使用 GetTypeData() 可以从 PTypeInfo ,例如:

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;

这篇关于如何在Delphi中使用RTTI或TypeInfo获取枚举的有效范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆