开发者

Have a getter return the value of a private var's property

开发者 https://www.devze.com 2022-12-19 06:51 出处:网络
开发者_如何学运维Say I have type TLight = class private Ftimer : TTimer; property IsAutoRotating: Boolean read Ftimer.Enabled;

开发者_如何学运维Say I have

type
  TLight = class
  private
    Ftimer : TTimer;
    property IsAutoRotating: Boolean read Ftimer.Enabled;

Obviously, this doesn't compile, but why not and how to solve this (preferably without keeping that state in a seperate var.


Your code won't compile because the property read and write specifiers must either refer to a field or method of the class. Ftimer.Enabled is neither of these.

To implement the IsAutoRotating property, you'll need to create a getter function:

type
  TLight = class
  private
    Ftimer : TTimer;
    function GetIsAutoRotating: Boolean;
  public
    property IsAutoRotating: Boolean read GetIsAutoRotating;
  end;

function TLight.GetIsAutoRotating : Boolean;
begin
  Result := Ftimer.Enabled;
end;


The getter and setter of a property should be a method of the class or it's parent - or - a field of the class or it's parent.

Since FTimer.Enabled is neither the above construct won't work. You might create a getter function and setter procedure that will return this property of FTimer (getter) and set this property of FTimer (setter):

type:

property Enabled: Boolean read GetEnabled write SetEnabled;

now press CTRL-SHIFT-C for class completion. The 2 methods are now created for you.

In the getter type:

Result := FTimer.Enabled;

In the setter type:

FTimer.Enabled := Value;

Et voila!

.

0

精彩评论

暂无评论...
验证码 换一张
取 消