代码之家  ›  专栏  ›  技术社区  ›  Mawg says reinstate Monica

如何使用“is”来检查类或确切的类(不是后代)?

  •  1
  • Mawg says reinstate Monica  · 技术社区  · 14 年前
    TBase = class(TObject)
    ...
    
    TDerived = class(Tbase)
    ...
    
    if myObject is TBase then ...
    

    3 回复  |  直到 14 年前
        1
  •  14
  •   kludg    14 年前

    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;
    
        2
  •  2
  •   A.Bouchez    14 年前

    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;
    

    class function TBase.IsDerivedClass: boolean;
    begin
      result := self=TDerivedClass;
    end;
    
        3
  •  1
  •   Zebedee    8 年前

    更好的方法;

    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;