Search code examples
delphiobjecttypestypeinfo

delphi type info of object


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


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;