在 Sprite 上使用 getter/setter 方法时出错

发布于 2024-11-27 16:13:35 字数 641 浏览 1 评论 0原文

我正在尝试创建一个扩展 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌上青苔 2024-12-04 16:13:35

您需要声明 Vehicle 的实例,因为 Sprite 不像 Movieclips 那样是动态的。

所以,这样做是行不通的:

var vehicle:Sprite = new Vehicle;
vehicle.speed = 5;

这应该行得通:

var vehicle:Vehicle= new Vehicle;
vehicle.speed = 5;

var vehicle:Sprite = new Vehicle;
Vehicle(vehicle).speed = 5; //We cast the vehicle instance to Vehicle type.

此外,我们可以使用 as 运算符进行转换:

var vehicle:Sprite = new Vehicle;
(vehicle as Vehicle).speed = 5; //We cast the vehicle instance to Vehicle type.

You need to declare the instance of the Vehicle as such, since Sprites are not dynamic as Movieclips.

So, doing this, does not work:

var vehicle:Sprite = new Vehicle;
vehicle.speed = 5;

This should work:

var vehicle:Vehicle= new Vehicle;
vehicle.speed = 5;

var vehicle:Sprite = new Vehicle;
Vehicle(vehicle).speed = 5; //We cast the vehicle instance to Vehicle type.

Also, we can cast using the as operator:

var vehicle:Sprite = new Vehicle;
(vehicle as Vehicle).speed = 5; //We cast the vehicle instance to Vehicle type.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文