清除TList或TObjectList [英] Clear a TList or a TObjectList

查看:122
本文介绍了清除TList或TObjectList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对于将对象存储在列表中使用什么感到有些困惑. 到目前为止,我已经使用TList并在循环中释放了每个项目.然后,我发现TObjectListFree自动执行此操作.然后我从TList.Clear的文档中看到了这一点:

I'm a bit puzzled of what to use for storing objects in a list. Until now I have used TList and freed each item in a loop. Then I discovered TObjectList that do this automatically from Free. Then I saw this from the doc of TList.Clear:

调用Clear清空Items数组并将Count设置为0. 释放用于存储Items数组的内存,并将Capacity设置为0.

Call Clear to empty the Items array and set the Count to 0. Clear also frees the memory used to store the Items array and sets the Capacity to 0.

所以基本上是一样的.所以

So it is basically the same. So

用于TList

mylist.Clear;
myList.Free;

TObjectList相同吗?

myList.Free;

TObjectList只能作为类用于项目还是可以存储记录?

Can TObjectList only be used for items as classes or can I store records?

推荐答案

1. TList不会同时使用ClearFree释放元素.

1. TList won't free the elements, with both Clear or Free.

aList.Clear;

aList.Clear;

只需设置aList.Count := 0而不释放aList.Items[]元素.因此,您将泄漏内存.您需要像这样的显式免费版本:

Will just set aList.Count := 0 without freeing the aList.Items[] elements. So you'll leak memory. You'll need an explicit free as such:

for i := 0 to aList.Count-1 do
  TObject(aList[i]).Free;

但这是TObjectList的工作...:)

But this is what TObjectList does... :)

关于TObjectList,值得一提的是TObjectList.Destroy正在呼叫Clear.

About TObjectList, it is worth saying that TObjectList.Destroy is calling Clear.

所以

aObjectList.Clear;
aObjectList.Free;

aObjectList.Free;

2.要存储记录列表,可以使用动态数组.

通过我们的

You'll get all TList methods (and more) with our dynamic array wrapper. That is, Add / Delete / Clear / Count / IndexOf / Find...

它具有内置的序列化功能(二进制或JSON),自动排序和比较(使用RTTI),而TList/TObjectList不存在.从Delphi 5及更高版本开始.

It has built-in serialization features (in binary or JSON), automated sorting and comparison (using RTTI) which are not existing with a TList/TObjectList. From Delphi 5 and later.

在Delphi的较新版本中,如果您不想使用第三方库,则可以使用泛型来处理动态数组.

With more modern version of Delp you may use generics to handle the dynamic array, if you do not want to use a third-party library.

这篇关于清除TList或TObjectList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆