gpt4 book ai didi

class - 使用 RTTI 混淆继承

转载 作者:行者123 更新时间:2023-12-03 18:04:07 24 4
gpt4 key购买 nike

如果问题不符合规则,请原谅我,但出于好奇,我只想知道为什么我的对象 classtype 让我感到困惑。

请看下面的代码:

 type 
TFirstClass = class
end;

TSecondClass = class(TFirstClass)
end;

TThirdClass = Class(TSecondClass)
End;

以上是我的类结构。

在一种方法中,我只想检查类对象的类类型。

    var
obj1: TFirstClass;
obj2: TSecondClass;
obj3 : TThirdClass;
str: string;
begin
obj1 := TSecondClass.Create;
obj2 := TThirdClass.Create;
try
if obj1 is TFirstClass then
str := str + ' obj1: first ||';

if obj1 is TSecondClass then
str := str + 'obj1 : Second ||';

if obj2 is TSecondClass then
str := str + 'obj2 : Second ||';

if obj2 is TThirdClass then
str := str + 'obj2 : Third ||';

ShowMessage(str);
finally
FreeandNil(Obj1);
FreeandNil(Obj2);
end;

end;

但是 str 中的结果是obj1:第一个 ||obj1:第二个 ||obj2:第二个 ||obj2:第三个 ||

为什么 is 关键字对所有 if 语句都返回 true?

最佳答案

documentation有答案:

The is operator, which performs dynamic type checking, is used to verify the actual runtime class of an object. The expression:

object is class

returns True if object is an instance of the class denoted by class or one of its descendants, and False otherwise.

他们的关键词是“或其后代之一”。

关于class - 使用 RTTI 混淆继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57275634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com