2007年3月31日星期六

The Dictionary Class

The Dictionary class (flash.utils.Dictionary) in ActionScript 3 is a new addition to ActionScript. Dictionary objects exactly like generic Object objects aside from one thing: Dictionary objects can use any value as a property name or key as opposed to a string.

Generic objects in ActionScript use string keys (names) for property definitions. If a non-string value is used as a key, the key interpretation is the string representation of that value. Example:

ActionScript Code:

var obj:Object = new Object();
obj[
"name"] = 1; // string key "name"
obj[
1] = 2; // key 1 (converted to "1")
obj[new
Object()] = 3; // key new Object() converted to "[object Object]"

for (var prop:String in obj) {
trace(prop); // traces: [object Object], 1, name
trace(obj[prop]); // traces: 3, 2, 1
}


If you attempt to use different objects as keys in generic objects, what you'll get iare string conversions that match each other. That means that though you have used separate objects as keys, to the object container, its the same key and they will reference the same value.

ActionScript Code:

var a:Object = new Object();
var b:
Object = new Object();

var obj:
Object = new Object();
obj[a] =
1; // obj["[object Object]"] = 1;
obj[b] =
2; // obj["[object Object]"] = 2;

for (var prop:String in obj) {
trace(prop); // traces: [object Object]
trace(obj[prop]); // traces: 2
}



The Dictionary class is not restricted to this limitation. You can have any value as a key and that value will fully represent that key as opposed to the object using its string representation. So in the above example, if a Dictionary instance is used, you would have two separate keys, one for each object.

ActionScript Code:

import flash.utils.Dictionary;

var a:
Object = new Object();
var b:
Object = new Object();

var dict:Dictionary = new Dictionary();
dict[a] =
1; // dict[a] = 1;
dict[b] =
2; // dict[b] = 2;

for (var prop:* in dict) {
trace(prop); // traces: [object Object], [object Object]
trace(dict[prop]); // traces: 1, 2
}



Though you still get [object Object] in the trace, this is a result of the string conversion in the trace command; it is a unique object key in the Dictionary instance.

Note that prop here is typed as *. This is important as the keys in the dict object can be of any type. If you used String for prop's type, it would cast the a and b objects as Strings when finding them in the loop making prop "[object Object]" instead of actual references to a and b which they would need to be to correctly obtain the values 1 and 2 through dict. For generic objects, regardless of the type used for prop, you will always get a String.

0 评论: