AS3仅接受给定类型的动态类

时间:2011-08-18 05:59:01

标签: actionscript-3 actionscript dynamic

是否可以在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有一种方法来操纵动态创建变量时运行的任何东西?

1 个答案:

答案 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]