AS3迭代类变量

时间:2012-11-08 18:02:23

标签: actionscript-3

如何迭代类实例的所有变量? 它似乎适用于常规对象......

编辑:这样做=)

var test:anyClass=new anyClass();
var someObject:Object={val1:"object string",val2:111,val3:new Date()};
var xmlList:XMLList=describeType(anyClass)..variable;
for each(var key:* in someObject)
    trace(String(key));
for each(var item:XML in xmlList)
    trace(String(test[item.@name]));

输出: 对象字符串 111 11月8日星期四11:19:27 GMT-0700 2012 类字符串 222 11月8日星期四11:19:27 GMT-0700 2012

public class anyClass
{
    public var val1:String="class string";
    public var val2:int=222;
    public var val3:Date=new Date();
}

1 个答案:

答案 0 :(得分:5)

我认为最简单的方法是使用flash.utils.describeType()

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/package.html#describeType()

这将返回一个描述类的所有详细信息的XML文档,然后您可以使用普通E4X进行攻击。这是我测试过的一个例子:

import flash.display.Sprite;
import flash.utils.describeType;

var test:String = "TEST";

function DescribeTypeExample():void {
    var child:Sprite = new Sprite();
    var description:XML = describeType(this);
    var variables:XMLList = description..variable;
    for each(var variable:XML in variables) {
        trace("VARIABLE: " + variable.@name);
        trace("VALUE: " + this[variable.@name]);
    }
}

this.DescribeTypeExample();

// Output:

// VARIABLE: test
// VALUE: TEST