1

由于内置 ActionScript 3 类中的一些限制(示例Dictionary),我希望构建一个添加此类内容的包装器。是否可以为我的自定义类保留以下语法,如果可以,如何?

var dic:MyDic = new MyDic();
dic[stuffy] = someObject;
4

1 回答 1

2

是的,您可以使用代理功能,但会产生性能开销:

import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.flash_proxy;

public class MyDict extends Proxy {
    private var _size:int = 0;
    private var _dict:Dictionary = new Dictionary();

    public function get size():int {
        return _size;
    }

    flash_proxy override function getProperty(name:*):* {
        return _dict[name];
    }

    flash_proxy override function setProperty(name:*, value:*):void {
        if (!_dict.hasOwnProperty(name))
            _size ++;
        _dict[name] = value;
    }

    flash_proxy override function deleteProperty(name:*):Boolean {
        if (_dict.hasOwnProperty(name)) {
            _size --;
            delete _dict[name];
            return true;
        }
        return false;
    }
}

var dict:MyDict = new MyDict();
dict[1] = 2;
dict["foo"] = "bar";
trace(dict.size, dict[1], dict["foo"]);

delete dict[1];
trace(dict.size, dict[1], dict["foo"]);
于 2010-03-05T14:27:58.960 回答