【问题标题】:Adding Append method to the generic TArray type将 Append 方法添加到泛型 TArray 类型
【发布时间】:2020-04-03 11:51:45
【问题描述】:

我正在尝试将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 错误] uMyArray.pas(18): E2008 不兼容类型

【问题讨论】:

  • 你为什么不用TList
  • 反模式的位,这会将数组的长度增加一。可能导致地址空间碎片化。
  • 你不应该一次追加一个元素。见stackoverflow.com/a/5756206/282848

标签: arrays delphi generics delphi-xe7


【解决方案1】:

您无法调整开放数组参数的大小。你需要通过TArray&lt;T&gt;

改变

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多