You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi继承类is类型判断存疑:为何多条件均返回True?

Why does the is keyword return True for all type checks in my Delphi code?

Let me break this down for you—this all comes down to how Delphi's is operator actually works, and it's a common point of confusion when you're first working with class inheritance.

First, let's recap your class hierarchy to set the stage:

type
  TFirstClass = class end;
  TSecondClass = class(TFirstClass) end;
  TThirdClass = Class(TSecondClass) End;

You've got a straight inheritance chain: TThirdClass inherits from TSecondClass, which in turn inherits from TFirstClass.

The key thing to remember is: the is operator doesn't check the declared type of your variable—it checks if the actual runtime type of the object the variable points to is compatible with the specified class. Compatibility here means the object is either an instance of the class itself, or any of its direct/indirect subclasses.

Let's walk through each of your checks one by one:

  • obj1 is TFirstClass: Even though obj1 is declared as TFirstClass, you created a TSecondClass instance and assigned it to obj1. Since TSecondClass is a subclass of TFirstClass, its instances are compatible with TFirstClass—so this check passes.
  • obj1 is TSecondClass: The actual runtime type of obj1 is exactly TSecondClass, so this is a perfect match and returns True.
  • obj2 is TSecondClass: obj2 is declared as TSecondClass, but you assigned a TThirdClass instance to it. TThirdClass inherits from TSecondClass, so its instances are compatible with the parent class—hence this check passes.
  • obj2 is TThirdClass: The actual runtime type of obj2 is exactly TThirdClass, so this is another perfect match that returns True.

If you ever need to check if an object's runtime type is exactly a specific class (not a subclass), you can use the ClassType property instead of is:

// This will return False, since obj1 is a TSecondClass, not TFirstClass
if obj1.ClassType = TFirstClass then ...

// This will return True
if obj1.ClassType = TSecondClass then ...

内容的提问来源于stack exchange,提问作者A B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:22:31