代码之家  ›  专栏  ›  技术社区  ›  Harriv

如何使用Delphi在cast中使用参数

  •  2
  • Harriv  · 技术社区  · 16 年前

    如何在Delphi中执行此操作:

    procedure ToggleVisibility(ControlClass : TControlClass);
    var
      i : integer;
    begin
      for i := 0 to ComponentCount - 1 do
        if Components[i] is ControlClass then
          ControlClass(Components[i]).Visible := not Control(Components[i]).Visible;
    end;
    

    我使用的是Delphi2007。

    4 回复  |  直到 16 年前
        1
  •  10
  •   mghie    16 年前

    因为组件是一个 TControl 或者你必须投靠的后代 控制 :

    procedure ToggleVisibility(ComponentClass : TControlClass);
    var
      i : integer;
    begin
      for i := 0 to ComponentCount - 1 do begin
        if Components[i] is ComponentClass then
          TControl(Components[i]).Visible := not TControl(Components[i]).Visible;
      end;
    end;
    
        2
  •  2
  •   Tihauan    16 年前
    (Components[i] as ComponentClass).Visible
    
        3
  •  2
  •   Lars D    16 年前

    所以问题是,您是否要反转TControl.Visible,那么您应该编写(Components[i]作为TControl.Visible)。我想这就是你想要的。

    如果要反转任何TControl子代的.Visible,不管它是否与控件相关,也不管它是否与TControl.Visible相关,那么您应该使用其他地方描述的RTTI解决方案。

        4
  •  1
  •   RRUZ    16 年前

    Uses
     TypInfo;
    
    procedure TForm1.ToggleVisibility(ComponentClass: TClass);
    var
      i       : integer;
      PropInfo: PPropInfo;
      aValue  : Variant;
    begin
      for i := 0 to ComponentCount - 1 do
        if Components[i] is ComponentClass then
         begin
          PropInfo := GetPropInfo(Components[i].ClassInfo, 'Visible');
          if Assigned(PropInfo) then
          begin
           aValue:=GetPropValue(Components[i], 'Visible');
           if PropInfo.PropType^.Kind=tkEnumeration then //All enumerated types. This includes Boolean, ByteBool, WordBool, LongBool and Bool
           SetOrdProp(Components[i], PropInfo, Longint(not Boolean(aValue)));
          end;
         end;
    end;
    

    执行

    ToggleVisibility(TEdit);