为动态数组设置边界

Setting bounds for dynamic arrays

静态数组允许定义它们的下限和上限:

StaticArray : array[5..7] of Integer;

我不知道如何在运行时用动态数组做同样的事情。

例如,如果我需要从静态数组中复制元素,并保持相同的索引,我不知道如何将其下限设置为 Low(StaticArray) 并将上限设置为 High(StaticArray):

var
  StaticArray : array[5..7] of Integer;
  DynamicArray : array of Integer;
  i : integer;
begin
  //initializing static array
  StaticArray[5] := 1;
  StaticArray[6] := 2;
  StaticArray[7] := 3;

  //setting the same length and bounds to the dynamic array
  //?

  //copying elements
  i := 0;
  for i := Low(StaticArray) to High(StaticArray) do
    DynamicArray[i] := StaticArray[i];
end;

有什么方法可以设置动态数组的 low/high 边界,还是它们总是将 0 作为下限,将 Length(Array) - 1 作为上限?

每当您对 Delphi 语言有疑问时,您应该查阅官方文档。在这种情况下,名为 Dynamic Arrays on Structured Types 的部分说明如下:

Dynamic arrays are always integer-indexed, always starting from 0.

Is there any way for setting the low/high bounds of a dynamic array

没有

or do they always have 0 as low bound and Length(Array) - 1 as high bound?

是的。这意味着您可以这样做:

var
  StaticArray : array[5..7] of Integer;
  DynamicArray : array of Integer;
  i : integer;
begin
  //initializing static array
  StaticArray[5] := 1;
  StaticArray[6] := 2;
  StaticArray[7] := 3;

  //setting the same length and bounds to the dynamic array
  SetLength(DynamicArray, Length(StaticArray));

  //copying elements
  for i := Low(StaticArray) to High(StaticArray) do
    DynamicArray[i-Low(StaticArray)] := StaticArray[i];
end;

或者,只使用两个单独的索引变量:

var
  StaticArray : array[5..7] of Integer;
  DynamicArray : array of Integer;
  i, j : integer;
begin
  //initializing static array
  StaticArray[5] := 1;
  StaticArray[6] := 2;
  StaticArray[7] := 3;

  //setting the same length and bounds to the dynamic array
  SetLength(DynamicArray, Length(StaticArray));

  //copying elements
  j := 0;
  for i := Low(StaticArray) to High(StaticArray) do begin
    DynamicArray[j] := StaticArray[i];
    Inc(j);
  end;
end;

或者,由于您的数组包含非托管的普通类型,只需将整个循环替换为单个 Move() 调用即可:

var
  StaticArray : array[5..7] of Integer;
  DynamicArray : array of Integer;
begin
  //initializing static array
  StaticArray[5] := 1;
  StaticArray[6] := 2;
  StaticArray[7] := 3;

  //setting the same length and bounds to the dynamic array
  SetLength(DynamicArray, Length(StaticArray));

  //copying elements
  Move(StaticArray[Low(StaticArray)], DynamicArray[0], Length(DynamicArray) * SizeOf(Integer));
end;