Is it possible to define a generic type Vector in Actionsctipt 3?

前端 未结 6 2061
遇见更好的自我
遇见更好的自我 2021-02-08 22:04

Hi i need to make a VectorIterator, so i need to accept a Vector with any type. I am currently trying to define the type as * like so:

var collection:Vector.<         


        
6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-08 22:50

    So it looks like the answer is there is no way to implicitly cast a Vector of a type to valid super type. It must be performed explicitly with the global Vector.<> function.

    So my actual problem was a mix of problems :)

    It is correct to use Vector. as a generic reference to another Vector, but, it cannot be performed like this:

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

    The assignment should be performed using the global Vector() function/cast like so:

    var spriteList:Vector. = new Vector.()
    var genericList:Vector. = new Vector.()
    genericList = Vector.(spriteList)
    
    
    

    It was a simple case of me not reading the documentation.

    Below is some test code, I would expect the Vector. to cast implicitly to 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++]
        }
    }
    

    提交回复
    热议问题