How can I determine if one TClass is received from another?

I am trying to do something like this:

function CreateIfForm ( const nClass : TClass ) : TForm; begin if not ( nClass is TFormClass ) then raise Exception.Create( 'Not a form class' ); Result := ( nClass as TFormClass ).Create( Application ); end; 

This leads to the error "Operator not applicable to this type of operand." I am using Delphi 7.

+6
source share
1 answer

First you need to check if you can change the function to accept only the form class:

 function CreateIfForm(const nClass: TFormClass): TForm; 

and get around the need for type checking and casting.

If this is not possible, you can use InheritsFrom :

 function CreateIfForm(const nClass: TClass): TForm; begin if not nClass.InheritsFrom(TForm) then raise Exception.Create('Not a form class'); Result := TFormClass(nClass).Create(Application); end; 
+17
source

Source: https://habr.com/ru/post/902119/


All Articles