ActionScript属性 - 公共Getter,受保护的Setter [英] ActionScript Property - Public Getter, Protected Setter
问题描述
有可能拥有一个公共getter和受保护的setter的属性吗?
Is it possible to have a property with a public getter and protected setter?
我有以下代码:
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.
}
}
health-= dmg; 但我拆分出来以获得有关编译器错误的更多详细信息。
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.
如果我使支持字段,getter和setter所有保护,它编译,但它不是我想要的结果;我需要外部可读的健康。
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.
推荐答案
不,访问者必须具有相同的权限级别。你可以让你的public
得到set函数,然后有一个受保护的setHealth,getHealth函数对。如果你愿意,你可以扭转它,但关键点是你有一组方法访问公共特权和另一个访问受保护的权限级别。
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.
这篇关于ActionScript属性 - 公共Getter,受保护的Setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!