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.
精彩评论