清除TList或TObjectList [英] Clear a TList or a TObjectList
问题描述
我对于将对象存储在列表中使用什么感到有些困惑.
到目前为止,我已经使用TList
并在循环中释放了每个项目.然后,我发现TObjectList
从Free
自动执行此操作.然后我从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 theCount
to 0.Clear
also frees the memory used to store theItems
array and sets theCapacity
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不会同时使用Clear
或Free
释放元素.
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屋!