Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if Delphi ClassType inherits from other ClassType?

In Delphi, given the following:

TFruit = class;
TFruitClass = class of TFruit;

TApple = class(TFruit);

TRedApple = class(TApple);

If I have a TFruitClass variable, how can I find out if it inherits from TApple? E.g. say I have

var
  FruitClass: TFruitClass;
...
FruitClass := TRedApple;

How can I verify that FruitClass does indeed inherit from TApple in this case? Using FruitClass is TApple only works for class instances.

like image 415
David Avatar asked Dec 14 '10 19:12

David


1 Answers

Use InheritsFrom:

if TApple.InheritsFrom(TFruit) then
  ...

You can also use

var
  Fr: TFruitClass;
  X: TObject;
begin
  if X.InheritsFrom(TFruit) then
    Fr := TFruitClass(X.ClassType);
end;
like image 184
Marjan Venema Avatar answered Nov 15 '22 02:11

Marjan Venema