Board index » delphi » Dynamic Type-Casting in Delphi

Dynamic Type-Casting in Delphi

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;

     David

 

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

Re:Dynamic Type-Casting in Delphi


Im Artikel <c774907e.0203031305.31e10...@posting.google.com>, ooh...@ort.org.il
(David Ohana) schreibt:

Quote
>  (obj as ct).InvokeSomeMethod();             // Compiler Error

ct must be a class type which has a method InvokeSomeMethod, at /compile/ time.

Methods may be incompatible even if two classes have methods of the same name,
but have no common ancestor class where exactly that method is declared. So the
compiler must know at compile time, which base class to use for the invocation
of a method. If you declared InvokeSomeMethod in TMyClass, then use (obj as
TMyClass).

Maarten already explained that in other words :-)

DoDi

Other Threads