简体   繁体   English

如何在使用Delphi的演员表中使用参数

[英]How to use argument in a cast with Delphi

How to do this in Delphi: 如何在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;

Compiler doesn't allow the cast in this case. 在这种情况下,编译器不允许强制转换。 Any ideas? 有任何想法吗?

I'm using Delphi 2007. 我正在使用Delphi 2007。

Since the component is a TControl or a descendant you have to cast to TControl : 由于组件是TControl或后代,因此必须TControl转换为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;
(Components[i] as ComponentClass).Visible

It does not make sense to cast ComponentClass(Components[i]).Visible, because .Visible needs to be of a specific class, in order to be compiled properly. 转换ComponentClass(Components [i])是没有意义的。可见,因为.Visible需要是特定的类,才能正确编译。 Therefore, you need to specify the exact class that should be cast to. 因此,您需要指定应该转换为的确切类。 For instance, if TControl has a .Visible property, but a derived class creates a new kind of .Visible property, the compiler would not know, which of these two properties it should compile for. 例如,如果TControl具有.Visible属性,但派生类创建了一种新的.Visible属性,则编译器不会知道它应编译哪两个属性。

So the question is, do you want to invert the TControl.Visible, then you should write (Components[i] as TControl).Visible. 所以问题是,你想要反转TControl.Visible,然后你应该写(Components [i]作为TControl).Visible。 I guess that's what you want. 我猜这就是你想要的。

If you want to invert the .Visible of any TControl descendent, no matter if it relates to the control being Visible or not, and no matter if it is related to TControl.Visible or not, then you should go for the RTTI solution described elsewhere. 如果你想反转任何TControl后代的.Visible,无论它是否与可见的控件有关,无论它是否与TControl相关。可见或不可用,那么你应该去其他地方描述的RTTI解决方案。

Try this option using the RTTI 使用RTTI尝试此选项

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;

To execute 执行

ToggleVisibility(TEdit);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM