开发者

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);
开发者_StackOverflow社区

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.


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;


I assume you pass the FruitClass variable along to some method, in which case your should read :

  if FruitClass.InheritsFrom(TApple) then

Note that you don't even need to test for nil, as InheritsFrom is a class function, and thus does not need the Self variable to be assigned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜