How can I tell if one TClass is derived from another?
Asked Answered
R

1

6

I'm 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 produces error "Operator not applicable to this operand type". I'm using Delphi 7.

Roeser answered 22/11, 2011 at 14:39 Comment(0)
F
18

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

function CreateIfForm(const nClass: TFormClass): TForm;

and bypass the need for type checking and casting.

If this isn't posssible, 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;
Forearm answered 22/11, 2011 at 14:52 Comment(3)
InheritsFrom! Yes, that's exactly what I'm looking for. ThanksRoeser
@Ulrich -- Your second answer is really the correct one: The function should never even accept a class that isn't a form.Amalita
@Nick, your right of course. I rephrased my answer to better reflect this.Forearm

© 2022 - 2024 — McMap. All rights reserved.