我该如何正确地写出这个?:
If number is different from Array[1] to Array[x-1] the begin...... 其中number是整数,array是从1到x的整数数组
发布于 2015-04-17 19:08:59
如果在数组MyArray中找不到number,我相信您会想要做些什么。然后你可以这样做:
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,你必须用begin Result := True; Exit; end替换Exit(True)。在较新版本的Delphi中,我想您也可以使用泛型之类的东西。
发布于 2018-11-30 10:23:30
您也可以编写泛型版本,但是您不能将泛型与独立的过程一起使用,它们需要绑定到类或记录。类似于下面的内容
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……
在Delphi10.3中,由于类型推断,您可以省略<integer>,这样看起来就像TArrayUtils.Contains(3, [1,2,3])。
https://stackoverflow.com/questions/29697432
复制相似问题