Delphi - 枚举类型的二进制 OR 值

问题描述 投票:0回答:1

我有从枚举类型声明的变量。我想将此枚举中的值二进制或值转换为变量。

type
  TValues = (vValue1 = $01, vValue2 = $02);

procedure BinaryOR;
var
  Value : TValues;
begin
  Value := Value or vValue1;
end;

但是 Delphi 似乎对此并不满意,因为它给出了编译器错误:

E2015 Operator not applicable to this operand type

我该如何去做呢?我的意思是我可以使用整数数据类型和或枚举中的值,但我更喜欢变量是枚举类型。

delphi enumeration
1个回答
0
投票

你正在尝试的事情是不可能以这种方式实现的。枚举类型的变量一次只能保存一个不同的值:

procedure EnumTest
type
  TValues = (vValue1 = $01, vValue2 = $02);
var
  Value : TValues;
begin
  Value := vValue1;
  Value := vValue2;
end;

如果要在一个变量中保存多个枚举值,可以使用

set
,如以下示例所示。但请注意,这些也不能
or
组合在一起!为此,您需要使用
integer
将枚举值类型转换为
Ord
,然后对这些值使用
or
运算符。

type
  TValues = (vValue1 = $01, vValue2 = $02);
  TValuesSet = set of TValues;
var
  Value: TValues;
  Values : TValuesSet;
  i: integer;
begin
  Values := [vValue1, vValue2];
  //or
  Include(Values, vValue1);
  Include(Values, vValue2);

  i := 0;

  // or'ing all the values in a set
  for Value in Values do
    i := i or Ord(Value);

  Writeln(i);

  // or'ing plain enum values
  i := Ord(vValue1) or Ord(vValue2);
  Writeln(i);
  Readln;
end.

输出:

3
3

© www.soinside.com 2019 - 2024. All rights reserved.