在Delphi中`this`关键字等效

Bil*_*dan 1 delphi pascal function-calls

假设我们有这个课程:

unit Traitement;

interface

type
  TTraitement =class
  public        
    function func1(param:String): String;
    function func2(param:String): String;
  end;

implementation

function TTraitement.func1(param:String): String;
begin
  //some code
end;

function TTraitement.func2(param:String): String;
begin
  //some code
end;

end.
Run Code Online (Sandbox Code Playgroud)

我想打电话func1给代码func2.好吧,我曾经是一名Java程序员,在这种情况下我会使用关键字this.Pascal是否具有this关键字的等价物?如果没有,我怎么能实现这种呼叫呢?

Dav*_*nan 6

相当于thisDelphi中的Java Self.从文档:

在方法的实现中,标识符Self引用调用该方法的对象.例如,以下是Classes单元中TCollection Add方法的实现:

function TCollection.Add: TCollectionItem;
begin
  Result := FItemClass.Create(Self);
end;
Run Code Online (Sandbox Code Playgroud)

Add方法调用由FItemClass字段引用的类中的Create方法,该字段始终是TCollectionItem后代.TCollectionItem.Create采用TCollection类型的单个参数,因此Add将TCollection实例对象传递给调用Add.这在以下代码中说明:

 var MyCollection: TCollection;
 ...
 MyCollection.Add   // MyCollection is passed to the 
                    // TCollectionItem.Create method
Run Code Online (Sandbox Code Playgroud)

由于各种原因,自我很有用.例如,类类型中声明的成员标识符可能会在其中一个类的方法的块中重新声明.在这种情况下,您可以将原始成员标识符作为Self.Identifier访问.

但请注意,问题中的示例代码无需使用Self.在该代码中,您可以func1通过func2省略来调用Self.

上述文档摘录中给出的例子确实为存在提供了正确的动机Self.