我怎样才能释放一个通用的TList<T>
?
我知道我可以使用TObjectList
with AOwnsObjects = True
在创建它的同时。
我很好奇,如何以通用方式重写以下方法,以便它可以免费T
when T
是非托管引用,是指针还是类?
procedure FreeList(const List: TList);
var
i: Integer;
begin
if (List = nil) then
Exit;
for i := Pred(List.Count) downto 0 do
if Assigned(List[i]) then
TObject(List[i]).Free;
List.Clear;
end;
您可以添加一个T
过程的通用参数(然后必须将其制成类方法才能使用泛型),并使用 RTTI 检查是否T
调用前是类类型Free()
在您的列表元素上。
例如:
type
ListUtils = class
public
class procedure ClearList<T>(const List: TList<T>);
end;
class procedure ListUtils.ClearList<T>(const List: TList<T>);
type
PObject = ^TObject;
var
i: Integer;
Value: T;
begin
if (List = nil) then
Exit;
if GetTypeKind(T) = tkClass then
// for older compilers that do not have GetTypeKind():
// if PTypeInfo(TypeInfo(T))^.Kind = tkClass then
begin
for i := Pred(List.Count) downto 0 do
begin
Value := List[i];
PObject(@Value)^.Free;
end;
end;
List.Clear;
end;
或者:
uses
..., System.Rtti;
type
ListUtils = class
public
class procedure ClearList<T>(const List: TList<T>);
end;
class procedure ListUtils.ClearList<T>(const List: TList<T>);
var
i: Integer;
begin
if (List = nil) then
Exit;
if GetTypeKind(T) = tkClass then
// for older compilers that do not have GetTypeKind():
// if PTypeInfo(TypeInfo(T))^.Kind = tkClass then
begin
for i := Pred(List.Count) downto 0 do
TValue.From<T>(List[i]).AsObject.Free;
end;
List.Clear;
end;
然后你可以像这样使用它:
var
IntList: TList<Integer>;
ObjList: TList<TSomeClass>;
begin
IntList := TList<Integer>.Create;
...
// does not call TObject.Free on list elements
ListUtils.ClearList<Integer>(IntList);
IntList.Free;
ObjList := TList<TSomeClass>.Create;
...
// calls TObject.Free on list elements
ListUtils.ClearList<TSomeClass>(ObjList);
ObjList.Free;
end;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)