在Delphi中,“this”的等效物是“Self”。您能否举几个例子来说明其用法?
在大多数情况下,你不应该在方法中使用self
。
事实上,在类方法中访问类的属性和方法时,就像有一个隐式的self.
前缀一样:
type
TMyClass = class
public
Value: string;
procedure MyMethod;
procedure AddToList(List: TStrings);
end;
procedure TMyClass.MyMethod;
begin
Value := 'abc';
assert(self.Value='abc'); // same as assert(Value=10)
end;
self
关键字用于将当前对象传递给另一个方法或对象。
例如:
procedure TMyClass.AddToList(List: TStrings);
var i: integer;
begin
List.AddObject(Value,self);
// check that the List[] only was populated via this method and this object
for i := 0 to List.Count-1 do
begin
assert(List[i]=Value);
assert(List.Objects[i]=self);
end;
end;
上面的代码将向TStrings
列表添加一个元素,其中List.Objects[]指向TMyClass实例。它还会检查所有列表项是否都是这种情况。
self.
前缀。实际上,IDE 智能感知功能允许您快速访问属性名称,或通过鼠标弹出提示或 Ctrl+单击查看声明 - 因此没有必要指定此前缀。如果您不在代码中定义全局变量(这是良好代码所必需的),则知道方法代码中的标识符是属性/方法名称。因此,在方法中不应使用 self.
前缀(除非在 with
语句内部)。 - Arnaud Bouchezend
因为我的IDE会为我完成,而且在法语键盘上键入begin
比{
键更快),但是self.
使得Python代码变得冗长。;) - Arnaud Bouchez
with
和将 Self 设置为 nil 是正交的。 - Rudy Velthuis