ActionScript 属性 - 公共 Getter、受保护的 Setter
是否有可能拥有一个具有公共 getter 和受保护 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.
}
}
我确实有 this.health -= dmg;
但我将其拆分以获取有关编译器错误的更多详细信息。
我不明白该属性如何在同一类中被视为只读。我也不明白为什么它无法访问。
如果我将支持字段、getter 和 setter 全部设置为受保护,它可以编译,但这不是我想要的结果;我需要健康状况可以从外部读取。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可以,访问者必须具有彼此相同的权限级别。您可以拥有您的公众
get 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.
由于您将仅从
Mob
类内部更新_health
,因此您可以编写一个私有函数来设置它。并保持公共吸气剂本身。
Since you will be updating
_health
from inside yourMob
class only, you can write a private function for setting it.And keep the public getter as such.
我不是专家,但我想你可能想使用
I'm no expert, but I think you may want to use