【发布时间】:2011-07-22 22:14:07
【问题描述】:
C++ 中“this”的 Delphi 等价物是什么?你能举一些它的使用例子吗?
【问题讨论】:
标签: delphi freepascal
C++ 中“this”的 Delphi 等价物是什么?你能举一些它的使用例子吗?
【问题讨论】:
标签: delphi freepascal
在delphi中Self相当于这个。它也可以按照here 中的说明进行分配。
【讨论】:
在大多数情况下,您不应在方法中使用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 intellisense 允许您快速访问属性名称,或者通过鼠标弹出提示或 Ctrl+Click 查看声明 - 因此无需指定此前缀。如果您没有在代码中定义全局变量(这是好的代码所必需的),您知道方法代码中的标识符是属性/方法名称。因此,您不应在方法中使用 self. 前缀(除非在 with 语句中)。
end,因为我的 IDE 为我完成了它,并且在法语键盘上输入 begin 比在 @987654332 上输入更快@ 键),但 self. 在 python 代码中让它变得冗长。 ;)