9

嗨,我需要制作一个 VectorIterator,所以我需要接受任何类型的 Vector。我目前正在尝试将类型定义为 *,如下所示:

var collection:Vector.<*> = new Vector<*>()

但是编译器抱怨该类型“不是编译时间常数”。我知道 Vector 类存在一个错误,错误报告将错误类型报告为缺失,例如:

var collection:Vector.<Sprite> = new Vector.<Sprite>()

如果没有导入 Sprite,编译器会抱怨找不到 Vector 类。我想知道这是否相关?

4

6 回答 6

7

所以看起来答案是没有办法将类型的 Vector 隐式转换为有效的超类型。它必须使用全局 Vector.<> 函数显式执行。

所以我的实际问题是混合问题:)

使用 Vector 是正确的。作为对另一个 Vector 的通用引用,但是,它不能像这样执行:

var spriteList:Vector.<Sprite> = new Vector.<Sprite>()
var genericList:Vector.<Object> = new Vector.<Object>()
genericList = spriteList // this will cause a type casting error

应该使用全局 Vector() 函数/强制转换来执行分配,如下所示:

var spriteList:Vector.<Sprite> = new Vector.<Sprite>()
var genericList:Vector.<Object> = new Vector.<Object>()
genericList = Vector.<Object>(spriteList)

这是我没有阅读文档的简单案例。

下面是一些测试代码,我希望是 Vector。隐式转换为 Vector.<*>。

public class VectorTest extends Sprite
{
    public function VectorTest()
    {
        // works, due to <*> being strictly the same type as the collection in VectorContainer
        var collection:Vector.<*> = new Vector.<String>() 

        // compiler complains about implicit conversion of <String> to <*>
        var collection:Vector.<String> = new Vector.<String>()
        collection.push("One")
        collection.push("Two")
        collection.push("Three")

        for each (var eachNumber:String in collection)
        {
            trace("eachNumber: " + eachNumber)
        }

        var vectorContainer:VectorContainer = new VectorContainer(collection)

        while(vectorContainer.hasNext())
        {
            trace(vectorContainer.next) 
        }
    }
}

public class VectorContainer
{
    private var _collection:Vector.<*>

    private var _index:int = 0

    public function VectorContainer(collection:Vector.<*>)
    {
        _collection = collection
    }

    public function hasNext():Boolean
    {
        return _index < _collection.length
    }

    public function get next():*
    {
        return _collection[_index++]
    }
}
于 2009-03-01T10:35:50.063 回答
1
[Bindable]
public var selectedItems:Vector.<Category>;

public function selectionChange(items:Vector.<Object>):void
{
    selectedItems = Vector.<Category>(items);
}
于 2011-10-20T11:47:18.470 回答
0

我相信你可以通过调用它来引用一个无类型的 Vector Vector(no .<>)

于 2009-03-02T09:08:46.800 回答
0

使用 Apache Flex 4.11.0,您已经可以为所欲为。它可能从 4.9.0 开始就存在了,但我之前没有尝试过。

于 2013-11-05T12:25:25.520 回答
-1
var collection:Vector.<Object> = new Vector.<Object>()

也许?但我只是猜测,没有尝试过。

于 2009-03-01T02:23:02.057 回答
-3
var collection:Vector.<Object> = new Vector.<Object>()

但仅针对 Flash Player 10 cs4

于 2009-03-01T06:12:55.687 回答