如何使用类型化的随机访问只读数组结构

时间:2012-05-20 21:47:20

标签: haxe

还在寻找Haxe的脚,我正在寻找一种方法来获得一个类似于数组的只读集合,我可以在编译时指定一个类型

理想情况下,我需要以下内容:

var collection:Collection<ItemType>;

var item:ItemType = collection[3];//or
var other:ItemType = collection.getAt(3);

//also, it would be good if it was iterable
for (item in collection)
{
//stuff
}

所以,就像一个数组,但只读。请问有人可以给我一些指示。

非常感谢

1 个答案:

答案 0 :(得分:2)

嗯,你不能拥有这样的只读数组访问权限,但你可以使用方法:

class ReadonlyArray<T> {
    var source:Array<T>;
    public function new(source) this.source = source
    inline function get(index) return source[index]
    inline function iterator() return index.iterator()
}

开销几乎不可察觉。