我该如何正确地写这个?:
If number is different from Array[1] to Array[x-1] the begin......
其中 number 是整数,array 是从 1 到 x 的整数数组
我相信如果在数组
number
中找不到MyArray
,你会想要做一些事情。然后你可以这样做:
NoMatch := True;
for i := Low(MyArray) to High(MyArray) do
if MyArray[i] = number then
begin
NoMatch := False;
Break;
end;
if NoMatch then
DoYourThing;
您可以创建一个函数来检查数组中是否找到数字。然后每次需要执行这样的检查时就可以使用这个函数。每一次,代码的可读性都会更高。例如,你可以这样做:
function IsNumberInArray(const ANumber: Integer;
const AArray: array of Integer): Boolean;
var
i: Integer;
begin
for i := Low(AArray) to High(AArray) do
if ANumber = AArray[i] then
Exit(True);
Result := False;
end;
...
if not IsNumberInArray(number, MyArray) then
DoYourThing;
如果您使用旧版本的Delphi,则必须将
Exit(True)
替换为begin Result := True; Exit; end
。在较新版本的 Delphi 中,我想您还可以使用泛型之类的东西。
我有同样的问题并这样解决:
if value in myArray then
...
但由于我需要与具体值进行比较,我只是这样做了:
if value in [0, 1, 2, 3] then
...
您还可以编写泛型版本,但是您不能将泛型与独立过程一起使用,它们需要绑定到类或记录。类似于下面的内容
unit Generics.ArrayUtils;
interface
uses
System.Generics.Defaults;
type
TArrayUtils<T> = class
public
class function Contains(const x : T; const anArray : array of T) : boolean;
end;
implementation
{ TArrayUtils<T> }
class function TArrayUtils<T>.Contains(const x: T; const anArray: array of T): boolean;
var
y : T;
lComparer: IEqualityComparer<T>;
begin
lComparer := TEqualityComparer<T>.Default;
for y in anArray do
begin
if lComparer.Equals(x, y) then
Exit(True);
end;
Exit(False);
end;
end.
用法是
procedure TForm6.Button1Click(Sender: TObject);
begin
if TArrayUtils<integer>.Contains(3, [1,2,3]) then
ShowMessage('Yes')
else
ShowMessage('No');
end;
应该使用
TArray<integer>
或 array of integer
等参数以及常量数组(如图所示) - 并且您可以向类添加许多其他方法,例如 IndexOf
或 Insert
...
从 Delphi 10.3 开始,由于类型推断,您可以省略
<integer>
,因此看起来像 TArrayUtils.Contains(3, [1,2,3])
。
begin
var Length := ArrLength(MyArray) - 1;
if Value in [MyArray[0] - MyArray[ArrLength]] then begin
ShowMessage('The Value in array!');
// do something
end;
end;