哇。属性比“它们只是 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;
控制访问
属性为您提供了只读/只写字段的简单概述。例如一个只读/不可变类:
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;
{ instead of }
A := MyStringList.Strings[i];
MyStringList.Strings[i] := B;
{ or }
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/设计时间属性等),但是这篇文章开始有点长了……
可以在这些网站上阅读更多内容: