如何检查整数是否可以转换为枚举类型值? [英] How to check if an integer can be converted to an enumeration type value?

查看:82
本文介绍了如何检查整数是否可以转换为枚举类型值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在枚举器类型上定义了 InRange 函数.如果传递的整数参数可以转换为枚举器类型,则该函数应返回 True .

I have defined an InRange function on my enumerator type. The function should return True if the passed integer parameter can be converted to the enumerator type.

  TMyEnum = (eA, eB);
  TMyEnumHelper = record helper for TMyEnum
    class function InRange(AValue : integer) : Boolean; static;
  end;

...

class function TMyEnumHelper.InRange(AValue : integer) : Boolean;
begin
  Result :=
    (AValue >= Low(TMyEnum)) and
    (AValue <= High(TMyEnum));
end;

在编译时,在(AValue> = Low(TMyEnum))行,出现以下错误:

On compilation, at the line (AValue >= Low(TMyEnum)), I get the following error:

[dcc32错误] Unit1.pas(34):E2008不兼容的类型

[dcc32 Error] Unit1.pas(34): E2008 Incompatible types

我做了一些测试,但是我真的不明白是怎么回事...即:

I did some tests but I really don't understand what's wrong... i.e:

  1. 我尝试将 InRange 函数的 AValue 参数类型切换为 Byte ShortInt Word SmallInt LongWord Cardinal LongInt Integer Int64 ,但在编译时会引发相同的错误.
  2. 如果我将枚举器定义为 TMyEnum = 0..1; ,则它将正确编译.
  1. I've tried switching the AValue parameter type of InRange function to Byte, ShortInt, Word, SmallInt, LongWord, Cardinal, LongInt, Integer and Int64, but it raises the same error on compiling.
  2. If I define the enumerator as TMyEnum = 0..1;, it compiles without errors.

推荐答案

您不能直接将枚举值与整数进行比较.您必须将枚举值转换为整数值才能进行比较:

You can't compare an enumerated value with an integer directly. You'll have to convert the enumerated value to an integer value in order to do the comparison:

class function TMyEnumHelper.InRange(AValue : integer) : Boolean;
begin
  Result :=
    (AValue >= Ord(Low(TMyEnum))) and
    (AValue <= Ord(High(TMyEnum)));
end;

请注意添加的"ord"强制转换,它将其参数"(括号内的表达式)转换为整数值.

Notice the added "ord" cast, which converts its "parameter" (the expression within the parentheses) to an integer value.

您的原因

TMyEnum = 0..1;

有用的是,这不是枚举,而是整数子范围,因此TMyEnum的基本类型是整数而不是枚举.

works is that this isn't an enumeration, but an integer sub-range, and thus the base type of TMyEnum is an integer and not an enumeration.

这篇关于如何检查整数是否可以转换为枚举类型值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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