Re:Dynamic Type-Casting in Delphi
Quote
David Ohana wrote in message ...
>I want to perform a dynamic type-casting (where the type to cast to is
>unknown at compile time), like in the following code, which cannot be
>compiled.
>Is this possible in Delphi ?
>procedure DoSomething (obj: TObject);
>var
> ct: TClass;
>begin
> ct := TMyClass;
> (obj as TMyClass).InvokeSomeMethod(); // Compiler OK
> (obj as ct).InvokeSomeMethod(); // Compiler Error
>end;
The guarantee is that ct is a TClass, meaning class of
TObject, or below, and you're probably using a method
that is not in TObject.
Using Click for an example, this method is introduced in
TControl. Declaring ct to be of TControlClass will allow
you to cast an object reference to it and call Click through
it. Declaring ct to be of TComponentClass, however, does
not - because the object may be a TComponent but not a
TControl, and then it does not have a Click method.
Groetjes,
Maarten Wiltink