gpt4 book ai didi

delphi - 如何检测组件已被释放?

转载 作者:行者123 更新时间:2023-12-03 15:06:48 26 4
gpt4 key购买 nike

我创建了一个组件,然后将主窗体上的面板传递给它。

这是一个非常简单的示例:

procedure TMy_Socket.StatusPanel_Add(AStatusPanel: TPanel);

此组件将根据需要更新面板标题。

在我的主程序中,如果我在下次组件尝试更新面板时FreeAndNil面板,我会得到一个AV。我明白原因:组件对面板的引用现在指向未定义的位置。

如何在组件内检测面板是否已被释放,以便我知道我无法引用它?

我尝试了if (AStatusPanel = nil),但它不是nil,它仍然有一个地址。

最佳答案

您必须调用面板的 FreeNotification() 方法,然后让您的 TMy_Socket 组件覆盖虚拟 Notification() 方法,例如(根据您的命名方案,我假设您可以向组件添加多个 TPanel 控件):

type
TMy_Socket = class(TWhatever)
...
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
...
public
procedure StatusPanel_Add(AStatusPanel: TPanel);
procedure StatusPanel_Remove(AStatusPanel: TPanel);
...
end;

procedure TMy_Socket.StatusPanel_Add(AStatusPanel: TPanel);
begin
// store AStatusPanel as needed...
AStatusPanel.FreeNotification(Self);
end;

procedure TMy_Socket.StatusPanel_Remove(AStatusPanel: TPanel);
begin
// remove AStatusPanel as needed...
AStatusPanel.RemoveFreeNotification(Self);
end;

procedure TMy_Socket.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (AComponent is TPanel) and (Operation = opRemove) then
begin
// remove TPanel(AComponent) as needed...
end;
end;

如果您一次只跟踪一个 TPanel:

type
TMy_Socket = class(TWhatever)
...
protected
FStatusPanel: TPanel;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
...
public
procedure StatusPanel_Add(AStatusPanel: TPanel);
...
end;

procedure TMy_Socket.StatusPanel_Add(AStatusPanel: TPanel);
begin
if (AStatusPanel <> nil) and (FStatusPanel <> AStatusPanel) then
begin
if FStatusPanel <> nil then FStatusPanel.RemoveFreeNotification(Self);
FStatusPanel := AStatusPanel;
FStatusPanel.FreeNotification(Self);
end;
end;

procedure TMy_Socket.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (AComponent = FStatusPanel) and (Operation = opRemove) then
FStatusPanel := nil;
end;

关于delphi - 如何检测组件已被释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com