无法使用对象的深层副本克隆矢量

时间:2014-08-07 18:04:10

标签: actionscript-3 vector clone

这是我想完全克隆的载体(意思是如果我改变克隆的载体,它不会影响原始载体)。

  var vector:Vector.<Path_Tiles> = new Vector.<Path_Tiles>();
  vector = path_finder.Find_Path(Gird.TILE_SET, start, end, R_G_B, SCAREDNESS);// return a vector of path_tiles in order

我想把它放到这个载体中

 var vector2:Vector.<Path_Tiles> = clone(vector);

和克隆方法是这个(我在网站上找到了这个方法,所以我不完全理解它)

   public function clone(source:Object):*
    {
        var myBA:ByteArray = new ByteArray();
        myBA.writeObject(source);
        myBA.position = 0;
        return(myBA.readObject());
    }

但是我收到了这个错误:“[Fault] exception,information = TypeError:Error#1034:Type Coercion failed:无法将 AS3 .vec :: Vector。@ 85973d1转换为 AS3 .vec.Vector ..“

如何将Path_Tiles转换为对象?

1 个答案:

答案 0 :(得分:1)

确保您的Path_Tiles课程已registered

flash.net.registerClassAlias("tld.domain.package.Path_Tiles", Path_Tiles);

然后,您可以通过将数据序列化为ByteArray来复制:

var tiles:Vector.<Path_Tiles>;
var tilesCloned:Vector.<Path_Tiles>;

var byteArray = new ByteArray();
byteArray.writeObject(tiles);
byteArray.position = 0;
tilesCloned = byteArray.readObject() as Vector.<Path_Tiles>;

使用readObject()关键字将Vector.<Path_Tiles>反序列化转换为as

序列化对象的构造函数必须接受默认参数。

要把这些放在一起,说这是你的Path_Tiles课程:

<强> Path_Tiles.as

package
{
public class Path_Tiles
{
    public function Path_Tiles(property1:String=null, property2:int=undefined) {
        this.property1 = property1;
        this.property2 = property2;
    }

    public var property1:String;
    public var property2:int;
}
}

这是您的主要课程,展示了深入克隆Path_Tiles集合的示例:

<强> Main.as

package
{
import flash.display.Sprite;
import flash.net.registerClassAlias;
import flash.utils.ByteArray;

public class Main extends Sprite
{
    public function Main() {
        super();

        var source:Vector.<Path_Tiles> = new <Path_Tiles>[
            new Path_Tiles("Hello", 1),
            new Path_Tiles("World", 2)
        ];

        var cloned:Vector.<Path_Tiles> = clone(source);
    }

    public function clone(source:Vector.<Path_Tiles>):Vector.<Path_Tiles> {
        flash.net.registerClassAlias("Path_Tiles", Path_Tiles);
        var byteArray = new ByteArray();
        byteArray.writeObject(source);
        byteArray.position = 0;
        return byteArray.readObject() as Vector.<Path_Tiles>;
    }
}
}

最后,我们可以看到对象被深层复制;由记忆地址确认:

vector-deep-copy

相关问题