TBase = class(TObject)
...
TDerived = class(Tbase)
...
if myObject is TBase then ...
我可以以某种方式对此进行编码,如果myObject是TDerived类,它会返回false吗?
答案 0 :(得分:14)
如果您需要精确的类类型检查,请使用ClassType方法:
type
TBase = class(TObject)
end;
TDerived = class(Tbase)
end;
procedure TForm1.Button1Click(Sender: TObject);
var
A: TBase;
begin
A:= TBase.Create;
if A.ClassType = TBase then ShowMessage('TBase'); // shown
A.Free;
A:= TDerived.Create;
if A.ClassType = TBase then ShowMessage('TBase again'); // not shown
A.Free;
end;
答案 1 :(得分:2)
您可以使用ClassType方法,或只检查Pointer(Object)^ = Class Type。
begin
A:= TBase.Create;
if A.ClassType = TBase then ShowMessage('TBase'); // shown
if PPointer(A)^ = TBase then ShowMessage('TBase'); // shown
A.Free;
A:= TDerived.Create;
if PPointer(A)^ = TBase then ShowMessage('TBase again'); // not shown
if A.ClassType = TBase then ShowMessage('TBase again'); // not shown
A.Free;
end;
如果您的代码在类方法中,则可以使用self来获取类值:
class function TBase.IsDerivedClass: boolean;
begin
result := self=TDerivedClass;
end;
答案 2 :(得分:1)
更好的方式;
type
TBase = class(TObject)
end;
TDerived = class(Tbase)
end;
procedure TForm1.Button1Click(Sender: TObject);
var
A, B: TObject;
begin
A:= TBase.Create;
if A.ClassType = TBase then ShowMessage('A is Exacly TBase'); // shown
if A is TBase then ShowMessage('A is TBase or SubClass of TBase'); // shown
if A is TDerived then ShowMessage('A is TDerived or SubClass of TDerived '); // NOT shown!!
A.Free;
B:= TDerived.Create;
if B.ClassType = TBase then ShowMessage('TBase again'); // not shown
if B is TBase then ShowMessage('B is TBase or SubClass of TBase'); // shown
if B is TDerived then ShowMessage('B is TDerived or SubClass of TDerived '); // shown!!
B.Free;
end;