在大多数情况下,您不应该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;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
上面的代码将向列表添加一个项目TStrings,其中 List.Objects[] 指向 TMyClass 实例。它将检查列表中所有项目的情况。
| 归档时间: |
|
| 查看次数: |
1350 次 |
| 最近记录: |