2

我需要释放存储在 ArrayList 中的对象列表。我知道你可以在 Delphi 中调用 Free 程序,但在 Delphi Prism 中没有免费程序。我不仅想从列表中删除对象,还想从内存中释放它。

例如说我有以下课程

TheClass = Class
 private
 theStr:String;
 protected
 public
end;

method TheForm;
begin
 TheArrayList:=new ArrayList;
end;

要添加对象,我会这样做:

method TheForm.AddToList;
var
 tmpObj:TheClass;
begin
 tmpObj := new TheClass;
 TheArrayList.Add(tmpObj);
end;

要从列表中删除对象,我会这样做,但没有免费的程序。

method TheForm.DeleteFromList;
var I:integer;
begin
 for I:=0 to theArrayList.count-1 do
 begin
  theClass(theArrayList[I]).free;     <-------I know this doesnt work.
  theArrayList.RemoveAt(I);
 end;
end;
end;

Delphi Prism中如何释放对象列表?

谢谢,

4

3 回答 3

4

由于您的类没有保留任何非托管资源,如文件、窗口句柄、数据库连接等。除了让 .net 垃圾收集器在确定时间合适时释放内存之外,您无需做任何事情。

试图强制垃圾收集器提前运行通常会导致性能更差,而不是简单地让它完成工作。

如果您有一个具有非托管资源的类,那么您应该遵循 IDisposable 模式

于 2011-09-06T14:28:42.280 回答
1
while theArrayList.count > 0 do
  theArrayList.RemoveAt(0);

GC 会帮助你。

于 2011-09-06T13:53:05.570 回答
1

Delphi Prism 程序在 .NET 上运行。不需要释放任何对象,因为垃圾收集器最终会这样做。正如有人已经评论过的那样,如果对象实现了它,您可以调用 IDisposable.Dispose() 来释放内存以外的其他资源。

还有 using 构造,有点像 Delphi 中的 Create-try-finally-Free-end:

using MyArrayList = new ArrayList do
begin
  // use ArrayList...
end; // IDisposable(ArrayList).Dispose is called, if applicable.

当然,这不适用于数组中的项目。如果你真的想要,你可以对它们中的每一个调用 Dispose。但一般来说,这不是必需的。

所以:

method TheForm.DeleteFromList;
begin
  theArrayList.Clear;
end;

无需释放任何东西。

于 2011-09-06T14:28:18.680 回答