Bef*_*rem 9 apache-flex generics vector actionscript-3
嗨我需要制作一个VectorIterator,所以我需要接受任何类型的Vector.我目前正在尝试将类型定义为*,如此:
var collection:Vector.<*> = new Vector<*>()
Run Code Online (Sandbox Code Playgroud)
但编译器抱怨类型"不是编译时常量".我知道Vector类存在一个错误,报告错误类型,例如:
var collection:Vector.<Sprite> = new Vector.<Sprite>()
Run Code Online (Sandbox Code Playgroud)
如果没有导入Sprite,编译器会抱怨它无法找到Vector类.我想知道这是否相关?
所以看起来答案是没有办法隐式地将类型的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
Run Code Online (Sandbox Code Playgroud)
应该使用全局Vector()函数/ cast来执行赋值,如下所示:
var spriteList:Vector.<Sprite> = new Vector.<Sprite>()
var genericList:Vector.<Object> = new Vector.<Object>()
genericList = Vector.<Object>(spriteList)
Run Code Online (Sandbox Code Playgroud)
这是一个简单的例子,我没有阅读文档.
下面是一些测试代码,我期待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++]
}
}
Run Code Online (Sandbox Code Playgroud)