检查组件是否为任何类型

时间:2013-02-12 06:43:22

标签: delphi

我正在尝试检查某个组件是TMachine还是TLabel,如果是这样,我希望它只要其NOT Label1或label2

就可以释放它

但它不允许我在ORif 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;

1 个答案:

答案 0 :(得分: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 ...名称