如何在Delphi Prism中释放对象的arraylist?

时间:2011-09-06 13:41:50

标签: delphi object arraylist free delphi-prism

我需要释放存储在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中完成释放对象列表?

谢谢,

3 个答案:

答案 0 :(得分:4)

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

试图强制垃圾收集器提前运行通常会导致性能下降,而不仅仅是让它完成工作。

如果您有一个包含非托管资源的课程,那么您应该follow the IDisposable pattern

答案 1 :(得分:1)

while theArrayList.count > 0 do
  theArrayList.RemoveAt(0);

GC会帮助你。

答案 2 :(得分: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;

无需任何游戏。