TObjectList E2003未声明的标识符TObjectList<>

时间:2013-11-19 16:20:20

标签: delphi delphi-xe2

我已经介绍过TObjectList,我想利用它,除了我似乎无法让sample code from Embarcadero's web site为我工作。这是我的代码:

unit Test03Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

type
  { Declare a new object type. }
  TNewObject = class
  private
    FName: String;

  public
    constructor Create(const AName: String);
    destructor Destroy(); override;
  end;

{ TNewObject }

var
  Form1: TForm1;

implementation

{$R *.dfm}

constructor TNewObject.Create(const AName: String);
begin
  FName := AName;
end;

destructor TNewObject.Destroy;
begin
  { Show a message whenever an object is destroyed. }
  MessageDlg('Object "' + FName + '" was destroyed!', mtInformation, [mbOK], 0);
  inherited;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  List: TObjectList<TNewObject>;
  Obj: TNewObject;
begin
  { Create a new List. }
  { The OwnsObjects property is set by default to true -- the list will free the owned objects automatically. }
  List := TObjectList<TNewObject>.Create();

  { Add some items to the List. }
  List.Add(TNewObject.Create('One'));
  List.Add(TNewObject.Create('Two'));

  { Add a new item, but keep the reference. }
  Obj := TNewObject.Create('Three');
  List.Add(Obj);

  {
    Remove an instance of the TNewObject class. Destructor
    is called for the owned objects, because you have set the OwnsObjects
    to true.
  }
  List.Delete(0);
  List.Extract(Obj);

  { Destroy the List completely--more message boxes will be shown. }
  List.Free;

end;

end.

尝试编译时,我收到错误[DCC错误] Test03Unit1.pas(51):E2003未声明的标识符:'TObjectList&lt;&gt;'。第51行是说:

List: TObjectList<TNewObject>;

我从未见过&lt; &GT;之前用过Pascal语言,所以这对我来说是一个全新的领域。在谷歌搜索“Delphi和&lt;&gt;”似乎没有告诉我我需要知道的事情。从other examples I can find on the internet开始,它似乎是使用它的正确方法。

使用Delphi XE2。

我做错了什么?

1 个答案:

答案 0 :(得分:5)

您必须将System.Generics.Collections添加到您的uses子句中。这是声明TObjectList<T>的单位。

我添加了答案的文档链接。如果找不到类,请在文档中查找。这将告诉你需要使用哪个单位。

TObjectList<T>外还有TList<T>。当您希望列表拥有其成员时,使用TObjectList<T>是有意义的。否则,使用TObjectList<T>没有任何好处,您也可以使用TList<T>。除了内置的Delphi通用容器外,还有许多出色的第三方容器。例如,Delphi Spring Framework有一个很好的容器集合。