0

我正在尝试检查组件是否是类型TMachine,或者TLabel 如果是,我希望它释放它,只要它不是 Label1 或 label2

但它不会让我做OR 任何if Components[I] is (TMachine) or (TLabel) then方法来解决这个问题?

    procedure TfDeptLayout.FormClose(Sender: TObject; var Action: TCloseAction);
var
  I: Integer;
begin
     for I := ComponentCount -1 downto 0 do
      begin
          if Components[I] is (TMachine) or (TLabel) then
              if Components[I].Name <> Label2.Name then
                if Components[I].Name <> label3.Name then
                  components[I].Free;
      end;
end;
4

1 回答 1

3

您不能or以这种方式使用,您还需要“重复” is

您也不需要使用 Components[I].Name,只需将 Components[I] 引用与 Label1 和 Label2 引用进行比较即可:

procedure TfDeptLayout.FormClose(Sender: TObject; var Action: TCloseAction);
var
  I: Integer;
begin
     for I := ComponentCount -1 downto 0 do
     begin
       if (Components[I] is TMachine) or (Components[I] is TLabel) then
         if Components[I] <> Label2 then
           if Components[I] <> label3 then
             components[I].Free;
      end;
end;

也可以(但可能不太可读)组合所有条件:

procedure TfDeptLayout.FormClose(Sender: TObject; var Action: TCloseAction);
var
  I: Integer;
  comp: TComponent;
begin
     for I := ComponentCount -1 downto 0 do
     begin
       Comp := Components[I];
       if (Comp is TMachine) then
         Comp.Free
       else if (Comp is TLabel) and (Comp <> Label2) and (Comp <> Label3) then
         Comp.Free;
     end;
end;

顺便说一句,最好给代码中引用的组件一个有意义的名称,而不是使用默认的 Label1、Label2... 名称

于 2013-02-12T06:56:54.837 回答