【问题标题】:How to free an arraylist of objects in a Delphi Prism?如何在 Delphi Prism 中释放对象的数组列表?
【发布时间】:2011-09-06 13:41:49
【问题描述】:

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

谢谢,

【问题讨论】:

  • 这是带有垃圾收集器的 .net。让它决定何时释放记忆。
  • @大卫,好的。但是如果有一种情况需要强制释放对象,而不是等待垃圾收集器。

标签: delphi object arraylist free delphi-prism


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:
    while theArrayList.count > 0 do
      theArrayList.RemoveAt(0);
    

    GC 会帮助你。

    【讨论】:

      【解决方案3】:

      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;
      

      无需释放任何东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-16
        • 1970-01-01
        • 1970-01-01
        • 2015-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多