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

标签 arrays delphi variant

我有一个表单,允许用户选择一条记录,然后该表单返回记录的 ID 以及调用表单可能需要的任意数量的字段值。为此,我有一个函数来处理创建选择表单并将所有值传入和传出调用表单:

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;

选择器表单具有以下公共(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;

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

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

最佳答案

当写入过程参数列表时,此代码

Var ARtnVals: Array of Variant

是一个开放数组,而不是动态数组。开放数组无法调整大小。开放数组在这里对您没有用处。

而是为数组定义一个类型:

type
  TDynamicArrayOfVariant = array of Variant;

使用该类型作为参数,这实际上最好作为输出参数:

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

然后向函数传递一个要填充的 TDynamicArrayOfVariant

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

关于arrays - Delphi 2007 和动态变量数组作为 Var 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31387040/

相关文章:

javascript - 将文本文件数据的第一列转换为 php 或 JSON

arrays - 如何按排序顺序获取重叠范围的计数?

sql - 来自 delphi 的 Access db 中的多个 INNER JOINS

arrays - VBA检查多维变量的整行是否为空而不循环

shopify - 如何在 Shopify 中显示元字段

python - 在 numpy 数组中搜索模式

javascript从其他嵌套对象填充嵌套对象

delphi - 有什么方法可以避免任务栏迷你窗口悬停时显示隐藏表单?

delphi - 设置 Canvas.LineTo 的线端样式

c++ - 在构造函数初始化列表中使用 std::variant