Delphi继承类is类型判断存疑:为何多条件均返回True?
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 thoughobj1is declared asTFirstClass, you created aTSecondClassinstance and assigned it toobj1. SinceTSecondClassis a subclass ofTFirstClass, its instances are compatible withTFirstClass—so this check passes.obj1 is TSecondClass: The actual runtime type ofobj1is exactlyTSecondClass, so this is a perfect match and returns True.obj2 is TSecondClass:obj2is declared asTSecondClass, but you assigned aTThirdClassinstance to it.TThirdClassinherits fromTSecondClass, so its instances are compatible with the parent class—hence this check passes.obj2 is TThirdClass: The actual runtime type ofobj2is exactlyTThirdClass, 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

