如何检查 class 的实例是否存在

How to check if an instance of a class exists

我有一个动态创建的 TComboBox。我有一个单独的过程,它使用此动态组件的 TStringList 中的项目。如何测试组件或实例是否已经存在?

请在您的回答中提供代码示例。谢谢!

private //private of form
 var
  cbxSortProfession : TComboBox;
  
 procedure cbxSortProfessionChange(Sender: TObject);
procedure SOME_PROCEDURE;
begin
    cbxSortProfession := TComboBox.Create();

    with cbxSortProfession do
    begin
      Parent := pnlSort;
      OnChange := cbxSortProfessionChange;
      left := 24;
      top := 232;
      width := 145;
      height := 21;
    end;
end;

您可以在 if 语句中使用 Assigned 函数,但一定要在销毁实例时将变量设置为 nil。

请注意,当您创建实例时,您可以将表单作为所有者参数传递。如果这样做,当实例被销毁时,表单的 notification procedure 将被调用。您应该覆盖它,然后您可以从那里将变量设置为 nil。

请注意,notification 过程是为表单拥有的每个组件的构造函数和析构函数调用的,因此您需要检查自己的组件。

我为 notification 过程创建了演示代码:

unit NotificationDemoMain;

interface

uses
    Winapi.Windows, Winapi.Messages,
    System.SysUtils, System.Variants, System.Classes,
    Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
    Vcl.ExtCtrls;

type
    TForm2 = class(TForm)
        CreateComboBoxButton: TButton;
        SortPanel: TPanel;
        Memo1: TMemo;
        FreeComboBoxButton: TButton;
        CheckComboBoxButton: TButton;
        procedure CheckComboBoxButtonClick(Sender: TObject);
        procedure CreateComboBoxButtonClick(Sender: TObject);
        procedure FreeComboBoxButtonClick(Sender: TObject);
    private
        FSortProfessionComboBox : TComboBox;
        procedure SortProfessionChange(Sender : TObject);
    protected
        procedure Notification(AComponent : TComponent;
                               Operation  : TOperation); override;
    end;

var
    Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.CheckComboBoxButtonClick(Sender: TObject);
begin
    if Assigned(FSortProfessionComboBox) then
        Memo1.Lines.Add('ComboBox is Assigned')
    else
        Memo1.Lines.Add('ComboBox doesn''t exists');
end;

procedure TForm2.CreateComboBoxButtonClick(Sender: TObject);
begin
    Memo1.Lines.Add('Create ComboBox');
    FSortProfessionComboBox := TComboBox.Create(Self);
    FSortProfessionComboBox.Parent := SortPanel;
    FSortProfessionComboBox.SetBounds(20, 20, 150, 21);
    FSortProfessionComboBox.Items.Add('Item 1');
    FSortProfessionComboBox.Items.Add('Item 2');
    FSortProfessionComboBox.Items.Add('Item 3');
    FSortProfessionComboBox.OnChange := SortProfessionChange;
end;

procedure TForm2.FreeComboBoxButtonClick(Sender: TObject);
begin
    FSortProfessionComboBox.Free;
    Memo1.Lines.Add('Free ComboBox');
end;

procedure TForm2.Notification(AComponent: TComponent; Operation: TOperation);
begin
    if Operation = opRemove then begin
        if (AComponent = FSortProfessionComboBox)  then
            FSortProfessionComboBox := nil;
    end;

    inherited;
end;

procedure TForm2.SortProfessionChange(Sender: TObject);
begin
    Memo1.Lines.Add('SortProfessionChange');
end;

end.