Mar*_*lka 6 delphi oop properties
我只是想知道为什么我应该在类中使用属性而不是"普通"变量(类属性?).我的意思是:
TSampleClass = class
public
SomeInfo: integer;
end;
TPropertyClass = class
private
fSomeInfo: integer;
public
property SomeInfo: integer read fSomeInfo write fSomeInfo;
end;
Run Code Online (Sandbox Code Playgroud)
有什么大不同?我知道我可以分别定义获取或保存属性的getter和setter方法,但即使没有变量是"属性",这也是可能的.
我试着搜索为什么要使用它,但没有任何有用的东西出现,所以我在这里问.
谢谢
这只是一个特定案例的一个非常简单的例子,但仍然是一个非常常见的案例.
如果您有可视控件,则可能需要在更改变量/属性时重新绘制控件.例如,假设您的控件具有BackgroundColor
变量/属性.
添加这样的变量/属性的最简单方法是让它成为一个公共变量:
TMyControl = class(TCustomControl)
public
BackgroundColor: TColor;
...
end;
Run Code Online (Sandbox Code Playgroud)
在TMyControl.Paint
程序中,您使用的值绘制背景BackgroundColor
.但这不行.因为如果更改BackgroundColor
控件实例的变量,则控件不会重新绘制自身.相反,直到下一次控件由于某些其他原因重绘自身时才会使用新的背景颜色.
所以你必须这样做:
TMyControl = class(TCustomControl)
private
FBackgroundColor: TColor;
public
function GetBackgroundColor: TColor;
procedure SetBackgroundColor(NewColor: TColor);
...
end;
Run Code Online (Sandbox Code Playgroud)
哪里
function TMyControl.GetBackgroundColor: TColor;
begin
result := FBackgroundColor;
end;
procedure TMyControl.SetBackgroundColor(NewColor: TColor);
begin
if FBackgroundColor <> NewColor then
begin
FBackgroundColor := NewColor;
Invalidate;
end;
end;
Run Code Online (Sandbox Code Playgroud)
然后使用控件的程序员必须使用MyControl1.GetBackgroundColor
获取颜色,并MyControl1.SetBackgroundColor
用于设置它.尴尬了.
使用属性,您可以充分利用这两个方面.的确,如果你这样做的话
TMyControl = class(TCustomControl)
private
FBackgroundColor: TColor;
procedure SetBackgroundColor(NewColor: TColor);
published
property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor;
end;
...
procedure TMyControl.SetBackgroundColor(NewColor: TColor);
begin
if FBackgroundColor <> NewColor then
begin
FBackgroundColor := NewColor;
Invalidate;
end;
end;
Run Code Online (Sandbox Code Playgroud)
然后
MyControl1.BackgroundColor
属性和来读取和设置背景颜色