哇,属性的含义远不止于“它们只是getter和setter方法的包装器”。
属性是一种优雅而强大的方式,可以提供对类字段的受控访问。
访问字段
正如已经说明的,您可以直接访问类字段。这非常好,并使代码更清晰。这也是实现类的可行第一个版本的一种很好的方式。
TMyClass = class
private
FValue: String
public
property Value: String read FValue write FValue
end
稍后,您可以重新设计您的类以使用方法验证和操作字段访问。公共接口仍然相同。
TMyClass = class
private
FValue: String;
procedure SetValue(AValue: String);
public
property Value: String read FValue write SetValue;
end;
procedure TMyClass.SetValue(AValue: String);
begin
if AValue = ''
then FValue := 'No value!'
else FValue := AValue;
end;
控制访问
Properties 可以方便地查看只读/写入字段。例如,一个只读/不可变类:
TClient = class
private
FName: String;
FSite: String;
FMail: String;
public
constructor Create(AName, ASite, AMail: String);
property Name: String read FName;
property Site: String read FSite;
property Mail: String read FMail;
end;
多态性
TClient = class
private
FName: String;
protected
function GetName: String; virtual; abstract;
public
property Name: String read GetName write FName;
end;
TImportantClient = class(TClient)
protected
function GetName: String; override;
end;
TArgumentativeClient = class(TClient)
protected
function GetName: String; override;
end;
function TImportantClient.GetName: String;
begin
Result := '+++ ' + FName;
end;
function TArgumentativeClient.GetName: String;
begin
Result := ':-( ' + FName;
end;
var
ClientA,
ClientB: TClient;
begin
ClientA := TImportantClient.Create;
ClientB := TArgumentativeClient.Create;
ClientA.Name := 'Mr. Nice';
ClientB.Name := 'Mr. Dumbhead';
ShowMessage(ClientA.Name);
ShowMessage(ClientB.Name);
end;
默认属性
在你的类中,你可以定义默认类字段,这意味着你可以直接访问该字段而无需指定属性名。
A := MyStringList[i]:
MyStringList[i] := B;
A := MyStringList.Strings[i];
MyStringList.Strings[i] := B;
A := MyStringList.GetString(i);
MyStringList.SetString(i, B);
索引
使用 Index
关键字,Delphi 将会将一个常量值作为参数传递给 getter/setter 方法。
TMyRect = class
private
FValues: Array[0..3] of Integer;
function GetProperty(Index: Integer): Integer;
public
property Top : Integer Index 0 read GetProperty;
property Left : Integer Index 1 read GetProperty;
property Width : Integer Index 2 read GetProperty;
property Height : Integer Index 3 read GetProperty;
end;
function TMyRect.GetProperty(Index: Integer): Integer;
begin
Result := FValues[Index];
end;
一些资源
还有一些主题需要涵盖(例如实现接口、存储值、RTTI / 设计时属性等),但这篇文章开始变得有点长了...
这些网站上可以阅读更多信息: