ActionScript Property - Public Getter, Protected S

2019-06-26 06:25发布

问题:

Is it possible to have a property with a public getter and protected setter?

I have the following code:

public class Mob extends Sprite {
    // snip

    private var _health:Number; // tried making this protected, didn't work
    public function get health():Number { return _health; }
    protected function set health(value:Number):void {
        _health = value;
    }

    // snip

    public function takeDamage(amount:Number, type:DamageType, ... additionalAmountAndTypePairs):void {
        var dmg:Number = 0;
        // snip
        var h:Number = this.health; // 1178: Attempted access of inaccessible property health through a reference with static type components.mobs:Mob.
        this.health = h - dmg; // 1059: Property is read-only.
    }
}

I did have this.health -= dmg; but I split it out to get more details on the compiler errors.

I don't understand how the property would be considered read-only within the same class. I also don't understand how it's inaccessible.

If I make the backing field, getter, and setter all protected, it compiles but it's not the result I want; I need health to be readable externally.

回答1:

No, accessors have to have the same privilege levels as each other. You can have your public get set functions, then have a protected setHealth, getHealth function pair. You could reverse it if you wish, but the key point is that you have one set of methods to access at a public privilege and another to access at a protected privilege level.



回答2:

Since you will be updating _health from inside your Mob class only, you can write a private function for setting it.

private function setHealth(value:Number):void
{
    _health = value;
}

And keep the public getter as such.



回答3:

I'm no expert, but I think you may want to use

internal var _health:Number;
public function get health():Number { return _health; }
internal function set health(value:Number):void { _health = value; }