AS3 - What's the difference between MyClass(instance) and (instance as MyClass)
You can upcast or downcast an instance (to a superclass or subclass) using this syntax:
var i:MyClass = MyClass(instance);
But what does the as
keyword do?
var i:MyClass = (instance as MyClass);
Are they equivalent? or am I miss开发者_高级运维ing something here...
To put it in a few words:
as
is an operator. The reference states: "If the first operand is a member of the data type, the result is the first operand. Otherwise, the result is the value null"- the latter attempts a conversion. For primitives, this basically works, for complex values, this throws an exception unless the value is a member of the required type.
suppose, you have a class A and a class B.
var s:String = "4a";
trace(s as int);//null
trace(int(s));//4
var b:B = new B();
trace(b as A);//null
trace(A(b));//throws an error
精彩评论