Delphi 2007 和动态变量数组作为 Var 参数

Delphi 2007 and Dynamic Variant Array as Var Parameter

我有一个表单允许使用 select 一条记录,然后这个表单 returns 记录的 ID 和调用表单可能需要的任意数量的字段值。为此,我有一个函数可以处理创建 select 表单并将所有值传入和传出调用表单:

Function Execute(AOwner: TComponent; AConnection: TADOConnection;
  AEditor: String; AButtons: TViewButtons; Var AID: Integer;
  Var ARtnVals: Array of Variant): TModalResult;
Var
  I: Integer;
Begin
  frmSelectGrid := TfrmSelectGrid.Create(AOwner);
  Try
    With frmSelectGrid Do
    Begin
      Connection := AConnection;
      Editor := AEditor;
      Buttons := AButtons;
      ID := AID;

      Result := ShowModal;
      If Result = mrOK Then
      Begin
        AID := ID;
        //VarArrayRedim(ARtnVals, Length(RtnVals));  !! Won't compile
        //SetLength(ARtnVals, Length(RtnVals));      !! Won't compile either
        For I := 0 To High(RtnVals) Do
          ARtnVals[I] := RtnVals[I];                 // Causes runtime exception
      End;
    End;
  Finally
    FreeAndNil(frmSelectGrid);
  End;
End;

selector 表单具有以下 public 属性:

public
  Connection: TADOConnection;
  Editor: String;
  Buttons: TViewButtons;
  ID: Integer;
  RtnVals: Array of Variant;
end;

然后在确定点击中,我有以下代码:

Var
  I, Idx, C: Integer;


  // Count how many fields are being returned
  C := 0;
  For I := 0 To Config.Fields.Count - 1 Do
    If Config.Fields[I].Returned Then
      Inc(C);

  // If no fields to be returned, then just exit.
  If C = 0 Then
    Exit;

  // Set the size of the RtnVals and assign the field values to the array.
  SetLength(RtnVals, C);
  Idx := 0;
  For I := 0 To Config.Fields.Count - 1 Do
    If Config.Fields[I].Returned Then
    Begin
      RtnVals[Idx] := aqItems.FieldByName(Config.Fields[I].FieldName).Value;
      Inc(Idx);
    End;

因此,一旦用户单击“确定”select 一条记录,RtnVals 数组就会填充要返回的字段的字段值。我现在需要将这些值复制到 Execute 函数中的 ARtnVals,以便它们返回到调用表单。

我的问题是如何设置 ARtnVals 数组的大小以便我可以复制字段? SetLength 的工作方式与上面的“确定”单击功能不同。 VarArrayRedim 也不起作用。

写在过程参数列表中时,这段代码

Var ARtnVals: Array of Variant

是一个开放数组,而不是动态数组。不能调整开放数组的大小。开阵在这里对你没用

改为为数组定义类型:

type
  TDynamicArrayOfVariant = array of Variant;

为您的参数使用该类型,这实际上最适合作为输出参数:

function Execute(..., out RtnVals: TDynamicArrayOfVariant): TModalResult;

然后传入函数aTDynamicArrayOfVariant进行填充

现在您在 Execute 中有了一个动态数组而不是一个开放数组,您可以使用 SetLength 来调整它的大小。