0

使用 Object 或 * 作为 Vector 的类型不提供通用功能(如 Java 中的 List)。见证:

public static function someGenericVectorUtil (value:Vector.<*>) :void {
    // do stuff to/with the Vector
}

var someVector:Vector.<Number>;
someGenericVectorUtil(someVector);  // compile-time implicit coercion error

所以,也许我们重新定义了实用方法来接受一个数组。但是没有简单的方法可以将进入实用程序的向量转换为数组,也没有简单的方法在之后将它们打包回来,导致代码如下:

public static function someGenericArrayUtil (value:Array) :void {
    // do stuff to/with the formerly-known-as-Vector
}

var someVector:Vector.<Number>;
var tempArray:Array = new Array(someVector.length);
for (var i:uint=0; i<someVector.length; i++) {
    tempArray[i] = someVector[i];
}
someGenericVectorUtil(tempArray);
someVector = Vector.<Number>([tempArray]);

不用说,这非常可怕。好的,让我们将 Vector-Array-Vector 废话移到实用程序中:

public static function vectorToArray (Vector.<*>) :Array {
    // oh wait....that Vector.<*> param is useless,
    // as demonstrated earlier.
}

有什么办法可以解决这个烂摊子吗?或者当我认为我可能需要通过通用实用程序运行 Vectors 时,我应该停止使用它们吗?(显然,也不是一个真正的选择......)

4

2 回答 2

3
public static function someGenericVectorUtil (value:Vector.<*>) :void {
    // do stuff to/with the Vector
}

var someVector:Vector.<Number>;
someGenericVectorUtil(Vector.<*>(someVector));

^ 它有效。也尝试使用数组。

于 2012-04-25T22:43:16.807 回答
1

这不是答案,而是对@Lukasz 答案的长评论。

The problem with his answer is that you're actually creating a new Vector, so you need to return the Vector from someGenericVectorUtil and re-cast it. E.g. try:

var v:Vector.<int> = Vector.<int>([1,2,3]); 
trace( v == Vector.<int>( Vector.<*>( v ) ) ); // traces false

That code just creates a simple Vector of ints, then compares it with a version of itself casted (first to *, then back to int). If you trace the Vectors out, they'll trace identical, but the actual Vectors references themselves aren't the same object. Thus if you have a utility function that modifies the Vector (e.g. a shuffle or randomise function), nothing will change.

E.g:

var v:Vector.<int> = Vector.<int>([1,2,3]);
trace( v ); // traces "1,2,3"

// shuffle() randomises the elements in a vector - this first call won't work
// as the cast creates a new vector
VectorUtil.shuffle( Vector.<*>( v ) );
trace( v ); // traces "1,2,3"

// we need to recast it back, and change shuffle() to return the vector
v = Vector.<int>( VectorUtil.shuffle( Vector.<*>( v ) ) );
trace( v ); // traces "3,1,2"

As you can see, it starts to get a bit ugly towards the end, and if you're keeping track of the Vector anywhere else, you'll need to update the references, but it's the only solution that I've found so far :S

于 2013-03-25T18:39:05.830 回答