Delphi中的实例引用?

W.K*_*K.S 6 delphi freepascal

在C++中Delphi相当于'this'是什么?你能举一些使用它的例子吗?

too*_*too 9

在delphi中,Self就相当于此.这也是分配中所描述这里.

  • 请注意,由于它是按值传递的,因此虽然可以完成,但分配给Self并不是很有用.它不会像某些人所期望的那样从构造函数中"返回"nil(构造函数实际上不会"返回"任何东西 - 赋值语法只是一种便利). (3认同)

Arn*_*hez 4

在大多数情况下,您不应该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 实例。它将检查列表中所有项目的情况。