我已经开始在Delphi XE中使用TCollection类,我发现在Delphi中使用TOwnedCollection后代的答案是一个很好的起点。TCollection 管理一个 TCollectionItems 列表。但是,我注意到 TCollection.Add 似乎没有将 TCollectionItem 添加到集合数组中,事实上我的测试似乎证实了这一点。代码本身是:
function TCollection.Add: TCollectionItem;
begin
Result := FItemClass.Create(Self);
Added(Result);
end;
FItemClass 是将要创建的对象类型,我认为添加到 TCollection 对象中。Add() 方法已弃用,似乎是旧的通知方法。我在任何地方都看不到结果被添加到集合中。应该如何将 TCollectionItem 添加到 TCollection?
TCollectionItem.Create(Collection: TCollection)
调用TCollectionItem.SetCollection
,这会将项目添加到Collection
:
procedure TCollectionItem.SetCollection(Value: TCollection);
begin
if FCollection <> Value then
begin
if FCollection <> nil then FCollection.RemoveItem(Self);
if Value <> nil then Value.InsertItem(Self);
end;
end;
之所以称为 TCollection.Add
,是因为它创建集合项,并且项构造函数将该项添加到包含的集合中。因此,TCollection.Add
确实创建了该项(在过程中将该项添加到自身),并返回对该新创建项的引用。(使用该引用来设置TCollectionItem
本身的属性。