问题描述
我在枚举器类型上定义了 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:
我做了一些测试,但是我真的不明白是怎么回事...即:
I did some tests but I really don't understand what's wrong...i.e:
- 我尝试将
InRange
函数的AValue
参数类型切换为Byte
,ShortInt
,Word
,SmallInt
,LongWord
,Cardinal
,LongInt
,Integer
和Int64
,但在编译时会引发相同的错误. - 如果我将枚举器定义为
TMyEnum = 0..1;
,则它将正确编译.
- I've tried switching the
AValue
parameter type ofInRange
function toByte
,ShortInt
,Word
,SmallInt
,LongWord
,Cardinal
,LongInt
,Integer
andInt64
, but it raises the same error on compiling. - 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.
这篇关于如何检查整数是否可以转换为枚举类型值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!