当前位置:  开发笔记 > 编程语言 > 正文

是否可以在Actionsctipt 3中定义泛型类型Vector?

如何解决《是否可以在Actionsctipt3中定义泛型类型Vector?》经验,为你挑选了1个好方法。

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

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

但编译器抱怨类型"不是编译时常量".我知道Vector类存在一个错误,报告错误类型,例如:

var collection:Vector. = new Vector.()

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



1> BefittingThe..:

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

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

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

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


应该使用全局Vector()函数/ cast来执行赋值,如下所示:

var spriteList:Vector. = new Vector.()
var genericList:Vector. = new Vector.()
genericList = Vector.(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.() 

        // compiler complains about implicit conversion of  to <*>
        var collection:Vector. = new Vector.()
        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++]
    }
}

推荐阅读
mobiledu2402851323
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有