How to do this in 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开发者_如何学Python := not Control(Components[i]).Visible;
end;
Compiler doesn't allow the cast in this case. Any ideas?
I'm using Delphi 2007.
Since the component is a TControl
or a descendant you have to cast to 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. 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.
So the question is, do you want to invert the TControl.Visible, then you should write (Components[i] as 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.
Try this option using the 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);
精彩评论