是否可以在AS3中使dynamic
类仅接受动态创建的属性(如果它们是给定类型?)
例如,我可能只想要允许精灵。所以请参考这个快速示例类:
public dynamic class Test extends Object{}
快速了解一下我的意思:
var test:Test = new Test();
test.something = 32; // error
test.something = "party hats"; // error
test.something = new Sprte(); // works
也许使用代理类/ namespsace有一种方法来操纵动态创建变量时运行的任何东西?
答案 0 :(得分:10)
测试类:
package classes {
import flash.display.Sprite;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public dynamic class Test extends Proxy {
private var _properties : Object;
public function Test() {
_properties = new Object();
}
override flash_proxy function getProperty(name : *) : * {
return _properties[name];
}
override flash_proxy function setProperty(name:*, value:*):void {
if (!(value is Sprite)) throw new Error("No Sprite given: " + value);
_properties[name] = value;
}
}
}
应用程序:
package classes {
import flash.display.Sprite;
public class TestTest extends Sprite {
public function TestTest() {
var test:Test = new Test();
try {
test.something = 32; // error
} catch (e : Error) {
trace (e);
}
try {
test.something = new Sprite(); // works
} catch (e : Error) {
trace (e);
}
trace (test.something);
}
}
}
输出:
Error: No Sprite given: 32
[object Sprite]