AS3 Dynamic class that only accepts a given type
Is it possible to make a dynamic
class in AS3 only accept dynamically created propert开发者_如何学Cies if they're a given type?
For example, I may only want Sprites to be allowed. So take this quick example class:
public dynamic class Test extends Object{}
-------
And a few quick lines to get an idea of what I mean:
var test:Test = new Test();
test.something = 32; // error
test.something = "party hats"; // error
test.something = new Sprte(); // works
Maybe using the proxy class/namespsace there's a way to manipulate whatever is run when creating variables dynamically?
The Test class:
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;
}
}
}
The App:
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);
}
}
}
The output:
Error: No Sprite given: 32
[object Sprite]
精彩评论