Self关键字在Delphi中用于指代当前对象的引用。它可以在类的方法和属性中使用。
示例用法:
- 在类的方法中,Self表示当前类的对象。
type
TMyClass = class
public
procedure MyMethod;
end;
procedure TMyClass.MyMethod;
begin
ShowMessage('The object is: ' + IntToStr(Integer(Self)));
end;
var
obj: TMyClass;
begin
obj := TMyClass.Create;
obj.MyMethod; // 显示对象的内存地址
obj.Free;
end;
- 在类的属性中,Self用于访问当前对象的其他属性。
type
TMyClass = class
private
FValue: Integer;
public
property Value: Integer read FValue write FValue;
function IsValueGreaterThan10: Boolean;
end;
function TMyClass.IsValueGreaterThan10: Boolean;
begin
Result := FValue > 10;
end;
var
obj: TMyClass;
begin
obj := TMyClass.Create;
obj.Value := 5;
if obj.IsValueGreaterThan10 then
ShowMessage('The value is greater than 10');
obj.Free;
end;
在上面的示例中,IsValueGreaterThan10方法使用Self关键字访问了当前对象的Value属性。如果Value属性的值大于10,则返回True。
总结:
Self关键字在Delphi中用于引用当前对象,可以用于访问当前对象的方法和属性。它可以在类的方法和属性中使用。