我们能说:
type
TPerson = class
private
pName : string;
public
property Name : string read pName write pName;
end;
Run Code Online (Sandbox Code Playgroud)
等于:
type
TPerson = class
private
pName : string;
public
procedure SetName(val: string);
function GetName:String;
end;
//{... implementing SetName And GetName...}
Run Code Online (Sandbox Code Playgroud)
??
请向我解释我们需要使用"财产"的地方,而不是.TNX
And*_*and 13
这都是关于班级设计的.从技术上讲,你可以用属性做"一切" ,你可以不用它们,但代码不会那么优雅.良好的设计也使课程更易于使用,并降低了犯错的风险.
首先,你的比较
TPerson = class
private
FName: string;
public
property Name: string read FName write FName;
end;
Run Code Online (Sandbox Code Playgroud)
至
TPerson = class
private
FName: string;
public
procedure SetName(const Name: string);
function GetName: string;
end;
Run Code Online (Sandbox Code Playgroud)
不太公平.实际上,在第一种情况下,当设置(或读取)值时,您没有机会做某事.所以更合适的比较是将后一个代码与之比较
TPerson = class
private
FName: string;
procedure SetName(const Name: string);
function GetName: string;
public
property Name: string read GetName write SetName;
end;
Run Code Online (Sandbox Code Playgroud)
例如,如果你编写一个控件,你经常需要在改变一个属性(比如,'毛衣颜色')时使控件无效(基本上重绘)TPerson.例如,
TPerson = class
private
FSweaterColor: string;
procedure SetSweaterColor(const Value: TColor);
public
property SweaterColor: TColor read FSweaterColor write SetSweaterColor;
end;
...
implementation
procedure TPerson.SetSweaterColor(const Value: TColor);
begin
if FSweaterColor <> Value then
begin
FSweaterColor := Value;
Invalidate; // causes a repaint of the control
end;
end;
Run Code Online (Sandbox Code Playgroud)
无论如何,属性有什么意义?好吧,基本上,重点是创建一个很好的类接口:它应该很容易用于对其实现细节不感兴趣的人.通过使用属性,您可以实现此目标.事实上,要阅读毛衣的当前颜色,你只需阅读Anna.SweaterColor,并设置它,你就是Anna.SweaterColor := clRed.您不知道这只是设置变量还是导致程序运行,而您并不在意.就您而言,TPerson对象只是具有可读且可选的属性SweaterColor.
您还可以创建只读(no write)或write-only(no read)属性.但无论你如何实现属性read和write(如果有的话)属性,从类用户的角度来看,属性看起来都是一样的.他不必记得使用SetSweaterColor或GetSweaterColor(事实上,他们是私人的,他无法访问),但只有SweaterColor财产.
这也暗示了使用属性的另一个好处.公共和已发布的属性对类的用户可见,而私有成员则不可用(如字段FSweaterColor和SetSweaterColor过程).这很好.因为现在你知道,类用户改变一个人的毛衣颜色的唯一方法是使用该SweaterColor属性,这保证将重新绘制控件.如果FSweaterColor变量是公共的,那么该类的用户可能会设置这个并且想知道,"当我改变毛衣颜色时,为什么没有发生任何事情?" 当然,你并不需要性能得到这个好处:私人FSweaterColor领域和公共GetSweaterColor和SetSweaterColor会做一样好,但你需要写一个GetSweaterColor即使不做任何处理,使色彩功能.此外,该类的用户需要学习使用两个标识符而不是一个.
更具体地说,如果使用Delphi IDE进行编程,您将看到published property(-y + ies)将出现在Object Inspector中,您可以在其中读取/更改它们(如果适用).如果不是属性,怎么可能呢?
所有这些都说,有时即使你可以,你也不会使用属性.例如,如果您具有只读"属性",则可以使用单个公共GetSomething函数而不是只读属性.毕竟,这可以节省一些编码.同样,如果您有一个只写属性,您可以使用单个公共SetSomething过程,这也将保存您的代码.最后,如果你有一个读/写属性不需要任何处理(既不得也不设置),你可以简单地使用一个公共变量!
所以,毕竟,你需要在逐个班级的基础上决定你班级的优秀设计.我想我的过长答案的简短版本类似于David的评论:
使用您喜欢的任何一个,以更方便的方式.