通过静态类型 Class 的引用调用可能未定义的方法 ''

Call to a possibly undefined method '' through a reference with static type Class

我在 Flash Professional 中制作了一个小的 .fla 文件,我在 Flash Professional 中添加了 .as(ActionScript 文件),并且我在 .as(ActionScript 文件)中添加了类似下面的代码,但是出现错误并且我想弄明白,但做不到,所以我决定改为 post 在这里。

package
{
    import flash.display.MovieClip;

    public class Bag extends MovieClip
    {
        static var firstBag:String;

        public static function set setFirstBag(value:String):void
        {
            firstBag = value;
        }

        public static function get getFirstBag():String
        {
            return firstBag;
        }
    }
}

我这样称呼它:

button1.addEventListener(MouseEvent.CLICK, onClickFirstButton);

function onClickFirstButton(e:MouseEvent):void
{
   Bag.setFirstBag("First slot in the bag has been filled up!");
}

但是我收到了以下错误:

Call to a possibly undefined method setFirstBag through a reference with static type Class.

我哪里做错了?

.as 文件和 .fla 文件在同一文件夹中。

如果我将 Bag class 更改为静态。错误将是这样的:

The static attribute may be used only on definitions inside a class.

非常感谢您的回答!

谢谢!

您正在使用 get 就像它是一种方法,但它们是属性访问器 do 而不是:

Bag.setFirstBag("First slot in the bag has been filled up!");

使用

Bag.setFirstBag ="First slot in the bag has been filled up!";

一些额外的想法...

虽然语法上有效,但您的 getter 和 setter 的定义和命名令人困惑且不典型,我认为这导致您对该行为感到困惑。您实际上已经定义了两个单独的属性,一个是只写的 ("setFirstBag"),一个是只读的 ("getFirstBag")。通常您将 getter/setter 定义为相同的 属性(例如 "firstBag"),并且 属性 名称中没有任何 "get" 或 "set",因为这就是 getter/setter 为您定义的内容。示例:

private static var _firstBag:String;
public static function get firstBag():String {
    return _firstBag:
}
public static function set firstBag(value:String):void {
    _firstBag = value;
}

// usage
Bag.firstBag = "stuff";
trace(Bag.firstBag); // "stuff"

此外,您可能有很好的理由在这里使用 getter/setter,或者您可能只是更喜欢它,但是根据您发布的代码,您可以定义一个 public static var 来做同一件事情。 (如果你这样做了,如果你需要一些副作用逻辑,那么重构为 getter/setter 将是微不足道的,因为 public API 保持不变。)