加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 为什么要在类中使用属??性?

发布时间:2020-12-15 04:21:24 所属栏目:大数据 来源:网络整理
导读:我只是想知道为什么我应该在类中使用属??性而不是“普通”变量(类属性?).我的意思是: TSampleClass = class public SomeInfo: integer;end;TPropertyClass = class private fSomeInfo: integer; public property SomeInfo: integer read fSomeInfo write f
我只是想知道为什么我应该在类中使用属??性而不是“普通”变量(类属性?).我的意思是:
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(TCustomControl)
public
  BackgroundColor: TColor;
...
end;

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

所以你必须这样做:

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

然后

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读