开发者

Instance reference in Delphi?

开发者_开发百科What's the Delphi equivalent of 'this' in C++? Could you please give some examples of its use?


In delphi Self is the equivalent of this. It is also assignable as described in here.


In most cases, you should not use self in the methods.

In fact, it's like if there was an implicit self. prefix when you access the class properties and methods, within a class method:

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;

The self is to be used when you want to specify the current object to another method or object.

For instance:

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;

this above code will add an item to the TStrings list, with List.Objects[] pointing to the TMyClass instance. And it will check this has been the case for all items of the List.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜