【问题标题】:TObjectList E2003 Undeclared identifier TObjectList<>TObjectList E2003 未声明的标识符 TObjectList<>
【发布时间】:2013-11-19 16:20:19
【问题描述】:

我已经被介绍到 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 Undeclared identifier: 'TObjectList'。第 51 行是这样的行:

List: TObjectList<TNewObject>;

我以前从未见过在 Pascal 语言中使用过 ,所以这对我来说是全新的领域。谷歌搜索“Delphi and ”似乎并没有告诉我我需要知道什么。从other examples I can find on the internet看来是正确的使用方式。

使用 Delphi XE2。

我做错了什么?

【问题讨论】:

    标签: delphi delphi-xe2


    【解决方案1】:

    您必须将System.Generics.Collections 添加到您的uses 子句中。也就是声明TObjectList&lt;T&gt;的单位。

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

    除了TObjectList&lt;T&gt;,还有TList&lt;T&gt;。当您希望列表拥有其成员时,使用TObjectList&lt;T&gt; 是有意义的。否则,使用TObjectList&lt;T&gt; 没有任何好处,您不妨使用TList&lt;T&gt;。除了内置的 Delphi 通用容器外,还有很多优秀的第三方容器往往更胜一筹。例如,Delphi Spring Framework 有很好的容器集合。

    【讨论】:

    • 非常感谢。我可以在 10 分钟内接受这个答案,但我现在要开车回家 - 到了那里我会接受的 :)
    猜你喜欢
    • 2015-11-30
    • 1970-01-01
    • 2012-06-27
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多