将 Append 方法添加到通用 TArray 类型

Adding Append method to the generic TArray type

我正在尝试将 Append 方法添加到 System.Generics.Collections.TArray 类型。

unit uMyArray;

interface

uses
  System.Generics.Collections;

type
  TArray = class(System.Generics.Collections.TArray)
  public
    class procedure Append<T>(var AValues: array of T; const AItem: T); static;
  end;

implementation

class procedure TArray.Append<T>(var AValues: array of T; const AItem: T);
begin
  SetLength(AValues, Length(AValues) + 1);
  AValues[Length(AValues) - 1] := AItem;
end;

end.

编译时 SetLength 行出现以下错误:

[dcc32 Error] uMyArray.pas(18): E2008 Incompatible types

您不能调整开放数组参数的大小。您需要通过 TArray<T>.

改变

class procedure Append<T>(var AValues: array of T; const AItem: T); static;

class procedure Append<T>(var AValues: TArray<T>; const AItem: T); static;