简体   繁体   中英

Enumerating class properties

I'm trying to iterate through the properties of a custom class, however, the methods provided by Adobe appear to not work. I'm not receiving compile or run-time errors.

Class

package {   
    public dynamic class enum {
        public var foo:Number = 123;

        public function enum() {
            this.setPropertyIsEnumerable("foo", true);
            if (this.propertyIsEnumerable("foo") == false) {
                trace("foo:" + foo + " is not enumerable.")
            }
        }
    }
}

// outputs "foo:bar is not enumerable."

Implementaiton

var test:enum = new enum();
for (var property:String in test) {
    trace(property);
}

// outputs nothing

I try to keep my code fast and flexible, so it's really frustrating when you must change the class to Dynamic just to be able to use for ... in on the properties. Jackson Dunstan's testing confirms that this can be 400x slower than static class properties , but those have to be explicitly referenced (impractical for property agnostic methods), or use reflection of the class (computationally expensive) to be accessible.

The only way I've found to sidestep the whole issue is to use dynamically declared variables... which is pointless since at that point using setPropertyIsEnumerable(prop, true) is superfluous; all dynamically created properties already are enumerable. Additionally, dynamic variables cannot be strongly datatyped, and performance goes out the window.

For example...

Class

package {   
    public dynamic class enum {
        public var foo:String = "apple";

        public function enum(){
            this.dynamicVar = "orange";
            this.dynamicProp = "banana";
            this.setPropertyIsEnumerable("foo", true);
            this.setPropertyIsEnumerable("dynamicProp", false);
        }
    }
}

Implementation

var test:enum = new enum();
for (var key:String in test) {
    trace(key + ": " + test[key]); // dynamicVar: 1
}

// outputs "dynamicVar: orange"

Now that the class is dynamic, we see that only one of our 3 test properties are being iterated. There should be 2.

It almost feels like Adobe wants us to adopt bad programming habits. Words fail me...

Non-dynamic classes do not provide enumerable properties or methods.

As stated in the description of the link you provided.

Sets the availability of a dynamic property for loop operations.

I think you might want to refactor your code on this approach. I have never had to loop over a classes properties like you are doing here. If you want to track items dynamically you should use an associative array and track them that way not at the class level like you are doing.
And if you want strong data typing then use a vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM