从字节数组</string>反序列化Vector。<string>

时间:2011-01-27 00:30:49

标签: flex actionscript air

我遇到了这种情况:

var vector:Vector.<String> = new Vector.<String>();
vector.push("uno");
vector.push("dos");
vector.push("tres");

var serializer:ByteArray = new ByteArray();
serializer.writeObject(vector);
serializer.position = 0;

var vector2:Vector.<String> = serializer.readObject();
trace(vector2[0]);
trace(vector2[1]);
trace(vector2[2]);

当代码到达trace(vector2[0]);句子时,我收到了这个错误:

TypeError: Error #1034: Type Coercion failed: cannot convert __AS3__.vec::Vector.<Object>@16820d01 to __AS3__.vec.Vector.<String>.

现在,如果我在声明registerClassAlias("com.some.alias", String)变量之前调用vector代码执行没有问题。

为什么在这种情况下需要拨打registerClassAlias()

1 个答案:

答案 0 :(得分:1)

writeObject()和readObject()方法分别写入(编码)并返回一个通用(无类型) Object 类型的对象。

所以将vector2键入为Vector。&lt;字符串&gt;将它键入为Vector时会导致错误。&lt;对象&gt;甚至根本不打字它应该工作;在这种情况下,将返回一个Object:

var vector:Vector.<Object> = new Vector.<Object>();//Object
vector.push( 'abc' );
vector.push( 123 );
vector.push( { foo:"bar" } );

var serializer:ByteArray = new ByteArray();
serializer.writeObject(vector);
serializer.position = 0;

var vector2:Object = serializer.readObject();// NB: readObject returns an Object
trace( 'vector2 is a Object ?', vector2 is Object );//true
trace( 'vector2 is a Vector.<Object> ?', vector2 is Vector.<Object> );//true but see below

trace( vector2[0], 'is a String ?', vector2[0] is String );//abc is a String ? true
trace( vector2[1], 'is a Number ?', vector2[1] is Number );//123 is a Number ? true  ( int and uints are Number )
trace( vector2[2] );//[object Object] untyped object
trace( 'vector2[2].foo => ', vector2[2].foo );// vector2[2].foo =>  bar
trace( 'vector2[2].bar => ', vector2[2].bar );// vector2[2].bar =>  undefined

有趣的是Vector。&lt;数字&gt;当读回时所有其他类型都失败的类型也被正确地键入,因为对象注释/取消注释下面的向量声明以查看解码后它是如何键入的。

//correctly typed
var vector:Vector.<Object> = new Vector.<Object>();
vector.push( 'abc', 123, { foo:"bar" } );

//var vector:Vector.<Number> = new Vector.<Number>();
//vector.push( 123, 456, 789 );

//generic Objects instead
//var vector:Vector.<String> = new Vector.<String>();
//vector.push( "a", "b", "c" );

//var vector:Vector.<Function> = new Vector.<Function>();
//vector.push( function a():*{}, function b():*{}, function c():*{} );

//var vector:Vector.<Boolean> = new Vector.<Boolean>();
//vector.push( true, false, true );

var serializer:ByteArray = new ByteArray();
serializer.writeObject(vector);
serializer.position = 0;

var vector2:* = serializer.readObject();
trace( 'vector2 is a Object ?', vector2 is Object );//true
trace( 'vector2 is a Vector.<Object> ?', vector2 is Vector.<Object> );
trace( 'vector2 is a Vector.<Number> ?', vector2 is Vector.<Number> );
trace( 'vector2 is a Vector.<String> ?', vector2 is Vector.<String> );
trace( 'vector2 is a Vector.<Function> ?', vector2 is Vector.<Function> );
trace( 'vector2 is a Vector.<Boolean> ?', vector2 is Vector.<Boolean> );

我不知道为什么Numbers也会这样做,但我对序列化知之甚少......