我正在学习 Delphi,阅读 Marco Cantu 的书,它非常完整。很清楚,但我对关键字
Self
有疑问。我已经有了 OOP 的经验并且掌握了它的基础知识。我的问题很简单。我可以将关键字 Self (Delphi) 与关键字 this (Java) 进行比较吗?
当我在书上读到关于内部记录中使用的
Self
时,我的脑海中浮现出类似Self : Delphi = this : Java
的东西。看看我创建的代码来进行测试:
type
TMarioKart = packed record
Character: String;
Kart: String;
Tires: String;
Speed: double;
Competitive: boolean;
private
air-speed: integer;
ground-speed: integer;
water-speed: integer;
public
constructor Create(Character: string);
function ShowStats(a: TMarioKart):string; overload;
function ShowStats(a: TMarioKart; b: TMarioKart): string; overload;
end;
我将剪掉代码的最大部分,我只在这里展示构造函数:
constructor TMarioKart.Create(Character: string);
begin
Self.Character := Character;
end;
这里使用关键字
Self
,我指的是记录的字符,而不是方法中传递的字符。这是使用自我的正确方法吗?难道是Java的this
的兄弟吗?
Self
与 Java、C++ 或 C# 中的 this
非常相似。然而,它被更多地调用,如下面的代码所示。
在 Delphi 中,您可以拥有非静态的
class
方法,但也有 Self
指针,显然该指针不是指向类的实例,而是指向调用该方法的类类型本身。
查看该程序的输出:
program WhatIsSelf;
{$APPTYPE CONSOLE}
type
TAnimal = class
procedure InstanceMethod;
class procedure ClassMethod;
class procedure StaticClassMethod; static;
end;
TDog = class(TAnimal)
end;
class procedure TAnimal.ClassMethod;
begin
Writeln(Self.ClassName);
end;
procedure TAnimal.InstanceMethod;
begin
Writeln(Self.ClassName);
end;
class procedure TAnimal.StaticClassMethod;
begin
// Writeln(Self.ClassName); // would not compile with error: E2003 Undeclared identifier: 'Self'
end;
var
t: TAnimal;
begin
t := TDog.Create;
t.InstanceMethod;
t.ClassMethod;
TAnimal.ClassMethod;
TDog.ClassMethod;
Readln;
end.
是的,Delphi 的
Self
是 Java 的 this
的直接类似物。
正式来说,
Self
是一个普通标识符(在某些情况下会自动预先声明)。
Self
是在方法和类方法的实现中自动定义的,其用途类似于前面提到的Java中的this
。底层技术类似于普通函数中的Result
变量。
换句话说,没有 self
关键字
S
编写)。只要您愿意(并且可以[*]),您都可以引入自己的
Self
变量、方法或类。type
// TForm1 ommitted
Self = class
function Self: Integer;
end;
function Self.Self: Integer;
begin
Result := SizeOf(Self);
end;
当然,在方法中实例化这种类型的对象会遇到困难,在这些情况下,您必须通过适配器函数(或过程)使用它:
function UseSelf: Integer;
var
S: Self;
begin
S := Self.Create;
Result := S.Self;
S.Free;
end;
function VarSelf: Integer;
var
Self: Integer;
begin
Self := SizeOf(Result);
Result := Self;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(UseSelf)+' '+IntToStr(VarSelf));
end;
您不能在方法中声明 Self
变量,因为已经存在这样的声明,而这正是错误所说的:
标识符重新声明:'Self'