我的代码如下
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;
它的类型安全时尚?或者更好的方法来完成这个案子?
感谢消化
答案 0 :(得分:4)
试试这个:
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;
答案 1 :(得分:-1)
操作员有时会误导。在您的情况下一切正常,因为检查的类来自层次结构的最后一行。但您的层次结构不正确。让我们考虑以下示例(将执行多少if?):
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;
在此示例中,您会收到: TLivingThing TAnimal THuman
如果你只想打个电话,那你错了。更好的解决方案是使用
if a.ClassName = TLivingThing.ClassName then ...
if a.ClassName = TAnimal.ClassName then ...
if a.ClassName = THuman.ClassName then ...
在这种情况下,如果将被调用。如果您使用if祖先和后代,这非常重要。