class - 使用 RTTI 混淆继承

标签 class delphi

如果问题不符合规则,请原谅我,但出于好奇,我只想知道为什么我的对象 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/

相关文章:

javascript - typescript :如何将对象映射到类型?

java - 看不懂Java普通类库的用法

python - 嵌套类是一种好习惯吗?

multithreading - 在 TThread.Execute 中调用 TDataModule 方法

cocoa - 是否可以比较2个sqlite文件并更新

类中的c++动态结构

javascript - 将静态变量和相关类移动到循环中

delphi - 在delphi中添加对象时,请弄清楚@和指针,而没有它们?

json - 如何使用 DBXJSON 将字符串与带有转义/特殊字符的 JSON 相互转换?

delphi - 以可变帧率逐帧创建 Motion JPEG