Delphi self keyword

前端 未结 4 496
陌清茗
陌清茗 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:40

    Formally speaking, Self is a normal identifier (that is automatically predeclared in some circumstances).

    Self is automatically defined in the implementation of methods and class methods and its purpose there is similar to this in Java as already mentioned. The underlying technology is analogous to the Result variable in ordinary functions.

    In other words, there is no self keyword (that's why it's typically written with an uppercase S). Whenever you want (and can [*]), you may introduce your own Self variable, method or class.

    type
      // TForm1 ommitted
    
      Self = class
        function Self: Integer;
      end;
    
    function Self.Self: Integer;
    begin
      Result := SizeOf(Self);
    end;
    

    You'll have of course difficulties to instantiate an object of this type within a method, in these cases, you have to use it through an adapter function (or procedure):

    function UseSelf: Integer;
    var
      S: Self;
    begin
      S := Self.Create;
      Result := S.Self;
      S.Free;
    end;
    
    function VarSelf: Integer;
    var
      Self: Integer;
    begin
      Self := SizeOf(Result);
      Result := Self;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      ShowMessage(IntToStr(UseSelf)+' '+IntToStr(VarSelf));
    end;
    
    

    [*] You cannot declare a Self variable within methods, because there is already such a declaration and that's exactly what the error says:

    Identifier redeclared: 'Self'

提交回复
热议问题