让我们说我们有这个课程:
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.
我想在func1
的代码中致电func2
。好吧,我曾经是一名Java程序员,在这种情况下,我会使用关键字this
。 Pascal是否具有this
关键字的等效项?如果没有,我怎么能实现这种呼吁?
答案 0 :(得分:6)
Delphi中Java的this
的等价物是Self
。来自documentation:
自
在方法的实现中,标识符Self引用 调用方法的对象。例如,这是 在Classes单元中实现TCollection Add方法:
function TCollection.Add: TCollectionItem; begin Result := FItemClass.Create(Self); end;
Add方法在由类引用的类中调用Create方法 FItemClass字段,始终是TCollectionItem后代。 TCollectionItem.Create采用TCollection类型的单个参数, 所以Add将调用Add的TCollection实例对象传递给它。 这在以下代码中说明:
var MyCollection: TCollection; ... MyCollection.Add // MyCollection is passed to the // TCollectionItem.Create method
自我因各种原因而有用。例如,一个成员 在类类型中声明的标识符可能在块中重新声明 其中一个方法。在这种情况下,您可以访问 原始成员标识符为Self.Identifier。
但请注意,问题中的示例代码无需使用Self
。在该代码中,您可以func1
从func2
拨打Self
,省略Self
。
上述文献摘录中给出的例子确实为Object oMove = object(DoorsID, mBasicCurrent);
Object oPrev = object(DestDoorsID, mBasicCurrent);
// move after
move(oMove, oPrev);
// move below
move(oMove, below oPrev);
的存在提供了正确的动机。