我有下面的代码

 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;



我如何检查上面代码的对象类型?我尝试了typeInfo,但消息从未执行
我如何进入儿童班公共领域?像这样?



TAnimal(livingThing).LegsCount = 3;


它的类型安全时尚?还是有更好的方法来完成此案例?

谢谢你的建议

最佳答案

试试这个:

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;

09-27 10:42