Skip to content
Delphi

泛型

在 Delphi 中使用类型安全的泛型容器。

#generics#collections

Code

delphi
uses
  System.Generics.Collections;

type
  TPair<T1, T2> = class
  private
    FFirst: T1;
    FSecond: T2;
  public
    property First: T1 read FFirst write FFirst;
    property Second: T2 read FSecond write FSecond;
    constructor Create(AFirst: T1; ASecond: T2);
  end;

// Generic collections
var
  List: TList<Integer>;
  Dict: TDictionary<string, TDateTime>;
begin
  List := TList<Integer>.Create;
  try
    List.Add(10);
    List.Add(20);
    List.Sort;  // type-safe sort
    // List.Add('text');  // compile error
  finally
    List.Free;
  end;

  Dict := TDictionary<string, TDateTime>.Create;
  Dict.Add('today', Now);
end;