Can I treat a class as a object type?
I have a custom class say class A :
class A
{
public testA:int;
public testB:int;
}
Now, I have a object say Object C , the object has the exact same names of variables and everythi开发者_JS百科ng as the class.
My question can I cast that object into class or vice versa. Instead of set/get of individual variables.
No you cannot cast an Object
into a Class
, but since a Class
is an Object
you can do the other way, but remember that accessing member from a Class
is faster that accessing member from an Object
.
To transform an Object
into a Class
you will have to instanciate the Class
and then copy each Object
field into that Class
. But beware they will not be the same instance it's a copy.
To make the reverse you will have to use describeType on the Class
to enumerate all the public field of that Class
, and then copy the value into a new Object
.
// simple sample:
class A {
public var testA:int;
public var testB:int;
}
function Object2A(o:Object):A {
var ret:A = new A();
for (var fieldName:String in o) {
if (ret.hasOwnProperty(fieldName)) {
ret[fieldName] = o[fieldName];
}
}
return ret;
}
import flash.utils.describeType;
function A2Object(a:A):Object {
var ret:Object = {};
var fields:XMLList=describeType(a).variable;
for each(var field:XML in fields) {
var fieldName:String=field.@name.toString();
ret[fieldName]=a[fieldName];
}
return ret;
}
var o:Object = {testA:12, testB:13};
var a:A = Object2A(o); // copy from object into class
o=A2Object(a); // copy from class into object
Unfortunately, no. The rules of duck-typing (if it looks like a duck and quacks like a duck, then it must be a duck) do not apply in AS3. Unless an object is explicitly constructed as type A, then a classification test will fail when compared to a generic object with the same properties. To cast generics into typed objects, I've always done this:
var obj = ((your generic object))
var a:A = new A();
for (var prop in obj) {
if (a.hasOwnProperty(prop)) a[prop] = obj[prop];
}
精彩评论