使用@:arrayAccess,但仍然 "Array access not allowed"

Using @:arrayAccess, but still "Array access not allowed"

我已经编写了以下(非常简单的)环形缓冲区 class,它应该允许通过 @:arrayAccess 宏访问数组:

class RingBuffer<T>
{
    private var _elements : Array<T> = null;

    public function new(p_numElements : Int, p_defaultValue : T)
    {
        _elements = new Array<T>();

        for (i in 0 ... p_numElements)
        {
            _elements.push(p_defaultValue);
        }
    }

    public function add(p_value : T) : Void
    {
        // Remove the first element
        _elements.splice(0, 1);
        _elements.push(p_value);
    }


    @:arrayAccess public inline function get(p_index : Int)
    {
      return _elements[p_index];
    }

    @:arrayAccess public inline function set(p_index : Int, p_value : T)
    {
        _elements[p_index] = p_value;
        return p_value;
    }
}

但是当我尝试在 class 的实例上使用数组访问时,我收到一条错误消息 "Array access is not allowed on...".

我是不是在使用宏时做错了什么?我基本上是在遵循示例 in the manual.

@:arrayAccess 只允许在摘要中使用(而不是 classes),这就是它在 Abstracts section of the Haxe manual 中的原因。您链接的那个页面还指出:

Nevertheless, with abstracts it is possible to define custom array access methods.

你可以做的是将 class 重命名为 RingBufferImpl 并创建一个名为 RingBufferabstract 来包装该类型并提供数组访问:

@:forward
@:access(RingBufferImpl)
abstract RingBuffer<T>(RingBufferImpl<T>) from RingBufferImpl<T>
{
    @:arrayAccess public inline function get(p_index : Int)
    {
      return this._elements[p_index];
    }

    @:arrayAccess public inline function set(p_index : Int, p_value : T)
    {
        this._elements[p_index] = p_value;
        return p_value;
    }
}

用法:

var buffer:RingBuffer<Int> = new RingBufferImpl<Int>(10, 0);
buffer[0] = 5;
for (i in 0...10)
    trace(buffer[i]);

请注意 @:arrayAcess 不是宏,而是 metadata - specifically built-in compiler metadata,如 : 所示。