获取对象的所有属性名称

时间:2012-01-17 16:19:50

标签: flex actionscript

假设我有一个看起来像这样的课程:

public class MyClass
{
    public var attribute1;
    public var attribute2;
}

我想将attribute1和attribute2作为字符串。我试过这个:

var test:MyClass = new MyClass();

for (var key:String in test)  
{
    trace(test[key]); 
}

但它不起作用,它永远不会进入循环。我怎么能做我想做的事?

由于

2 个答案:

答案 0 :(得分:3)

  

for..in循环仅枚举动态添加的属性。声明的变量和类的方法不在for..in循环中枚举。这意味着ActionScript API中的大多数类都不会在for..in循环中显示任何属性。

对于解决方案,请阅读:

http://livedocs.adobe.com/flex/3/html/help.html?content=usingas_8.html

答案 1 :(得分:0)

你需要使用AS反射/内省 本机方式是使用describeType函数,如下所示:

public function getDetails():void { 
        var classInfo:XML = describeType(button1);

        // List the class name.
        ta1.text = "Class " + classInfo.@name.toString() + "\n";

        // List the object's variables, their values, and their types.
        for each (var v:XML in classInfo..variable) {
            ta1.text += "Variable " + v.@name + "=" + button1[v.@name] + 
                " (" + v.@type + ")\n";
        }
    }

(来自flex doc:http://livedocs.adobe.com/flex/3/html/help.html?content=usingas_8.html

我不确定,但我认为类mx.utils.ObjectUtil可以使它更简单。它仍然是原生的方式。

另一种选择是使用库来简化它 看一下:http://www.as3commons.org/as3-commons-reflect/introduction.html

相关问题