在 Sprite 上使用 getter/setter 方法时出错
我正在尝试创建一个扩展 Sprite 的类,附加一些私有属性,并能够使用 getter 和 setter 读取和写入这些属性。 很简单...但是编译器会抛出此错误“通过静态类型 flash.display:Sprite 的引用访问可能未定义的属性速度。” 如果我将类设置为扩展 MovieClip 对象,它就会起作用。 有人可以向我解释一下这背后的逻辑吗?为什么我不能在 Sprite 中使用 getter 和 setter?
这是示例代码:
package {
import flash.display.Sprite;
public class Vehicle extends Sprite{
private var _speed:uint = 3;
public function get speed():uint {
return _speed;
}
public function set speed(value:uint):void {
_speed = value;
}
public function Vehicle() {
super();
}
}
}
I'm trying to make a class that extends the Sprite, have some private properties attached to it and be able to read and write those properties using getters and setters.
Simple... but the compiler throw this error "Access of possibly undefined property speed through a reference with static type flash.display:Sprite."
It works if I set my class to extend the MovieClip object.
Could someone explain me the logic behind this? why I can't use getter and setters with a Sprite?
Here is a sample code:
package {
import flash.display.Sprite;
public class Vehicle extends Sprite{
private var _speed:uint = 3;
public function get speed():uint {
return _speed;
}
public function set speed(value:uint):void {
_speed = value;
}
public function Vehicle() {
super();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要声明 Vehicle 的实例,因为 Sprite 不像 Movieclips 那样是动态的。
所以,这样做是行不通的:
这应该行得通:
此外,我们可以使用
as
运算符进行转换:You need to declare the instance of the Vehicle as such, since Sprites are not dynamic as Movieclips.
So, doing this, does not work:
This should work:
Also, we can cast using the
as
operator: