Delphi   发布时间:2022-04-11  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了delphi – 为什么要在类中使用属​​性?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我只是想知道为什么我应该在类中使用属​​性而不是“普通”变量(类属性?).我的意思是:
TSampleClass = class
  public
    SomeInfo: Integer;
end;

TPropertyClass = class
  private
    fSomeInfo: Integer;
  public
    property SomeInfo: Integer read fSomeInfo write fSomeInfo;
end;

有什么大不同?我知道我可以分别定义获取或保存属性的getter和setter方法,但即使没有变量是“属性”,这也是可能的.

我试着搜索为什么要使用它,但没有任何有用的东西出现,所以我在这里问.

谢谢

解决方法

这只是一个特定案例的一个非常简单的例子,但仍然是一个非常常见的案例.

如果您有可视控件,则可能需要在更改变量/属性时重新绘制控件.例如,假设您的控件具有BACkgroundColor变量/属性.

添加这样的变量/属性的最简单方法是让它成为一个公共变量:

TMyControl = class(TCustomcatontrol)
public
  BACkgroundColor: TColor;
...
end;

在TMyControl.Paint过程中,使用BACkgroundColor的值绘制背景.但这不行.因为如果更改控件实例的BACkgroundColor变量,则控件不会重新绘制自身.相反,直到下一次控件由于某些其他原因重绘自身时才会使用新的背景颜色.

所以你必须这样做:

TMyControl = class(TCustomcatontrol)
private
  FBACkgroundColor: TColor;
public
  function GetBACkgroundColor: TColor;
  procedure SetBACkgroundColor(NewColor: TColor);
...
end;

哪里

function TMyControl.GetBACkgroundColor: TColor;
begin
  result := FBACkgroundColor;
end;

procedure TMyControl.SetBACkgroundColor(NewColor: TColor);
begin
  if FBACkgroundColor <> NewColor then
  begin
    FBACkgroundColor := NewColor;
    Invalidate;
  end;
end;

然后程序员使用控件必须使用MyControl1.GetBACkgroundColor来获取颜色,并使用MyControl1.SetBACkgroundColor来设置它.尴尬了.

使用属性,您可以充分利用这两个方面.的确,如果你这样做的话

TMyControl = class(TCustomcatontrol)
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;

然后

>从程序员的角度来看,他可以使用单个标识符,MyControl1.BACkgroundColor属性读取和设置背景颜色,以及>当他设置它时,控件重新粉刷!

大佬总结

以上是大佬教程为你收集整理的delphi – 为什么要在类中使用属​​性?全部内容,希望文章能够帮你解决delphi – 为什么要在类中使用属​​性?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。