Question

I have code like below

 TLivingThing=class
 end;

 THuman=class(TLivingThing)
 public
   Language:String
 end;

 TAnimal=class(TLivingThing)
 public
   LegsCount:integer;
 end;


 procedure GetLivingThing()
 var
   livingThing:TLivingThing;
 begin
   livingThing:=THuman.Create();
   if livingThing=TypeInfo(THuman) then ShowMessage('human');

   livingThing:=TAnimal.Create();
   if livingThing=TypeInfo(TAnimal) then ShowMessage('animal');
 end;
  1. how can I check type of object like above code? I tried typeInfo but message never executed

  2. How can I access child class public field? just like this?

TAnimal(livingThing).LegsCount=3;

its type safe-fashion? or any better way to accomplish this case?

thanks for sugestion

Was it helpful?

Solution

Try this:

procedure GetLivingThing();
var
  livingThing:TLivingThing;
  human:THuman;
  animal:TAnimal;
begin
  livingThing:=THuman.Create();
  try

    if livingThing is THuman then
    begin
      human:=livingThing as THuman;
      ShowMessage('human');
    end;

    if livingThing is TAnimal then
    begin
      animal:=livingThing as TAnimal;
      ShowMessage('animal');
    end;

  finally
    livingThing.Free;
  end;
end;

OTHER TIPS

Operator is sometimes misleads. In your case all is ok because classes which are checked are from last row of hierarchy. But your hierarchy isn't correct. Let consider following example (how many ifs will be executed?):

TLivingThing = class
end;
TAnimal = class(TLivingThing)
end;
THuman = class(TAnimal)
end;
TWolf = class(TAnimal)
end;

procedure Check;
var 
   a: THuman;
begin
a := THuman.Create;
if a is TLivingThing then 
   begin
   MessageBox('TLivingThing');
   //Do something useful here
  end;
if a is TAnimal then 
   begin
   MessageBox('TAnimal');  
   //Do something useful here  
   end;
if a is THuman then 
   begin
   MessageBox('THuman');
   //Do something useful here
   end;
end;

In this example you receive: TLivingThing TAnimal THuman

If you wanted call only one if, you are wrong. Better solution is use

if a.ClassName = TLivingThing.ClassName then ...
if a.ClassName = TAnimal.ClassName then ...
if a.ClassName = THuman.ClassName then ...

In this case proper if will be called. This is very important if you use in if chain ancestors and descendants.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top