簡體   English   中英

TObjectList E2003未聲明的標識符TObjectList <>

[英]TObjectList E2003 Undeclared identifier TObjectList<>

我已經被介紹給TObjectList,並且我想利用它,除了我似乎甚至無法從Embarcadero網站上獲得示例代碼來為我工作。 這是我的代碼:

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 <>。 第51行是這樣寫的:

List: TObjectList<TNewObject>;

我以前從未見過在Pascal語言中使用過<>,因此對我來說這是全新的領域。 用谷歌搜索“ Delphi和<>”似乎並不能告訴我我需要知道些什么。 其他示例中,我可以在互聯網上找到它,似乎是使用它的正確方法。

使用Delphi XE2。

我究竟做錯了什么?

您必須將System.Generics.Collections添加到uses子句。 那就是聲明TObjectList<T>

我已經為答案添加了文檔鏈接。 當找不到類時,請在文檔中查找。 這將告訴您您需要使用哪個單位。

TObjectList<T>還有TList<T> 當您希望列表擁有其成員時,可以使用TObjectList<T> 否則,使用TObjectList<T>沒有任何好處,而您也可以使用TList<T> 除了內置的Delphi通用容器之外,還有許多優秀的第三方容器,它們通常是上乘的。 例如, Delphi Spring框架具有很好的容器集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM