flash - 有没有办法让Flash强制静态类型?

标签 flash actionscript-3

有没有办法让flash as3编译器需要静态类型?我有一个不这样做的坏习惯,最好让它抛出编译器错误。在 as3 的发布设置中,我打开了“严格”​​,但这并没有真正改变任何东西。

最佳答案

我有点困惑。这不会给您带来任何编译时错误吗:

function enforceType(var_a:int, var_b:String) {
    trace("passed");
}

enforceType(1, 'test');
enforceType(1, 1);
enforceType('test', 1);

这对我来说确实如此。

编辑
既然您编辑了问题,我将编辑我的答案。
AS3 IS静态类型如果您显式键入变量。

示例:

var a:int = 0;
a = "TEST";
//  a is typed as an int, therefor when you attempt to compile the above, 
//  you will get a compile time error 
//  1067: Implicit coercion of a value of type String to an unrelated type int.

var a = 0;
a = "TEST";
//  Here, a is not typed explicitly, so you can assign whatever type you want, and
//  the compiler will not complain.

所以,简而言之,如果您愿意的话,AS3 是静态类型的。无法让编译器知道您实际想要分配的类型,因为它在编译期间是静态类型。

想象一下,例如,您在类 Foo 中定义了一个非类型化静态变量 bar。

package 
    class Foo {
        public static var bar;
    }   
}

现在,您可以在程序中的两个不同位置访问 Foo。这两个不同的访问点基于由于用户交互(例如鼠标单击)而触发的事件。在您的两个事件处理程序中,您有以下内容:

// In one handler you have
Foo.bar = 1;
// and in another handler
Foo.bar = "test";

编译器无法知道哪个将首先运行,因为它们都基于用户交互。编译器所能做的就是说:如果发生这种情况,可以吗?在这种情况下,由于没有输入 bar,所以没关系。

如果 Foo 类更改为:

package 
    class Foo {
        public static var bar:String;
    }   
}

然后编译器就会知道上面列出的第一个事件处理程序是不行的,因为 bar 已被静态类型化为 String。

长话短说(以及要吸取的教训):改掉坏习惯并开始输入变量。你会很高兴你这么做了。

For reference .

关于flash - 有没有办法让Flash强制静态类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4404109/

相关文章:

javascript - 如何实现Flash的播放或暂停?

javascript - 我可以调整来自 iframe 的 swf 对象的大小吗?

flash - 在 AS3 方法中接受多个参数

actionscript-3 - 什么是 Haxe 的 Adob​​e Flash 符号库?

flash - 如何在不影响比例的情况下调整影片剪辑的大小?

actionscript-3 - 当外部文件中的数字更改时播放声音

c# - 如何播放放置在 Resources 文件夹中的 SWF 文件

actionscript-3 - Const 及其影响

arrays - 将 string.Split (',' ) 转换为 int 数组

apache-flex - 弹性 : Loading assets into externally loaded modules