我正在使用德尔福 XE2。我构建了一个自定义TComboBox
,以便我可以轻松地添加键/字符串对并在组件的析构函数中处理清理。
为简洁起见,省略了所有代码。if not (csDesigning in ComponentState)
interface
type
TKeyRec = class(TObject)
Key: string;
Value: string;
end;
TMyComboBox = class(TComboBox)
public
destructor Destroy; override;
procedure AddItemPair(const Key, Value: string);
end;
implementation
destructor TMyComboBox.Destroy;
var i: Integer;
begin
for i := 0 to Self.Items.Count - 1 do
Self.Items.Objects[i].Free;
Self.Clear;
inherited;
end;
procedure TMyComboBox.AddItemPair(const Key, Value: string);
var rec: TKeyRec;
begin
rec := TKeyRec.Create;
rec.Key := Key;
rec.Value := Value;
Self.Items.AddObject(Value, rec);
end;
当应用程序关闭时,将调用析构函数,但该Items.Count
属性不可访问,因为TComboBox
必须有父控件才能访问该属性。调用析构函数时,它不再具有父控件。
我以前看到过这个问题,不得不将对象单独存储并单独TList
释放它们。但这仅起作用,因为我将它们添加到的顺序TList
始终与添加到组合框中的字符串相同。当用户选择一个字符串时,我可以使用组合框索引在TList
. 如果组合框已排序,则索引将不匹配,因此我不能总是使用该解决方案。
有没有其他人看过这个?你是如何解决这个问题的?能够在组件的析构函数中释放对象真是太好了!