Delphi self keyword

前端 未结 4 502
陌清茗
陌清茗 2021-01-02 06:56

I am learning Delphi reading Marco Cantu\'s book and it\'s super complete. It\'s very clear but I have a doubt about the keyword self. I already have experience

4条回答
  •  再見小時候
    2021-01-02 07:31

    Self is very similar to this in Java, C++, or C#. However it is a little bit more invoked, as the following code will show.

    In Delphi, you can have class methods that are not static but also have a Self pointer, which then obviously does not point to an instance of the class but to the class type itself that the method is called on.

    See the output of this program:

    program WhatIsSelf;
    
    {$APPTYPE CONSOLE}
    
    type
      TAnimal = class
        procedure InstanceMethod;
        class procedure ClassMethod;
        class procedure StaticClassMethod; static;
      end;
    
      TDog = class(TAnimal)
      end;
    
    class procedure TAnimal.ClassMethod;
    begin
      Writeln(Self.ClassName);
    end;
    
    procedure TAnimal.InstanceMethod;
    begin
      Writeln(Self.ClassName);
    end;
    
    class procedure TAnimal.StaticClassMethod;
    begin
    //  Writeln(Self.ClassName); // would not compile with error: E2003 Undeclared identifier: 'Self'
    end;
    
    var
      t: TAnimal;
    begin
      t := TDog.Create;
      t.InstanceMethod;
      t.ClassMethod;
    
      TAnimal.ClassMethod;
      TDog.ClassMethod;
    
      Readln;
    end.
    

提交回复
热议问题