我有一个字节数组[0..2]。我需要检查一个字节是否在该数组中。但是,当使用if ($52 in byteArray) then
时,我遇到错误"运营商没有超载"。我已经尝试将另一个变量设置为一个字节,然后在语句中使用它,但仍然得到错误。这是一个非常简单的程序,显示了这一点:
program overloaded;
var
byteArray: array[0..2] of Byte;
begin
byteArray[0] := $00;
byteArray[1] := $69;
byteArray[2] := $52;
if ($52 in byteArray) then
writeLn('We will not get to this point');
end.
这将无法使用FPC 3.0.2中的上述错误进行编译。
答案 0 :(得分:0)
您有两种选择,即重载运算符或使用for。
program ByteArrayIteration;
var
ByteArray: array[0..2] of Byte = ($00, $69, $52);
SomeByte : Byte = $52;
begin
for SomeByte in byteArray do
if SomeByte = $52 then
begin
WriteLn('We will get to this point');
Break;
end;
end.
过载替代方案:
program OverloadInOperator;
uses SysUtils;
operator in(const A: Byte; const B: TBytes): Boolean;
var
i: Integer;
begin
Result := True;
for i := Low(B) to High(B) do if A = B[i] then Exit;
Result := False;
end;
var
Bytes : TBytes;
AByte : Byte = $52;
begin
Bytes := TBytes.Create($41, $52, $90);
if AByte in Bytes then WriteLn('Done');
end.
如果您的用例限制为每个数组255个项目,请考虑使用集合。
program SetOfByte;
var
Bytes : set of Byte = [$41, $52, $90];
AByte : Byte = $52;
begin
if AByte in Bytes then WriteLn('Done');
end.