as3中通过ByteArray进行对象的深度拷贝

作者:网络 来源:佚名 更新时间:2009-08-09 13:32:25 点击:

今天同事问我有as3中对象深度拷贝的问题

原来还真是没用过,今天google后自己总结下,便于大家参考

as3中通过bytearray可以进行对象的深度拷贝

import flash.utils.bytearray;
import flash.utils.getqualifiedclassname;
import flash.net.*;
import src.*;
function cloneobject(source:object) :* {
var typename:string = getqualifiedclassname(source);//获取全名
trace(”输出类的结构”+typename);
//return;
var packagename:string = typename.split(”::”)[0];//切出包名
trace(”类的名称”+packagename);
var type:class = getdefinitionbyname(typename) as class;//获取class
trace(type);
registerclassalias(packagename, type);//注册class

//复制对象
var copier:bytearray = new bytearray();
copier.writeobject(source);
copier.position = 0;
return copier.readobject();
}

有的人说用复制对象那一段不就可以了吗,但是实际上行不通
对于数组深度复制来说, 复制对象的后面4句代码就足够了

var a1:array=[1,2,3];

var a2:array =cloneobject(a1);

var a3:array = a1;
a1.push(”youmila”);
trace(”a1:”+a1+”a2:”+a2+”a3′+a3);

但是对于对象来说肯定不行

用列子测试下
src.youmila.as 代码:

package src{
public class youmila{
private var $_name:string =”youmila”;
private var $_num:number =0;
public function youmila():void{
trace($_name);

}

public function secondfunc():void{
$_num++;
trace(”this a called function $_num::”+$_num);

}
}

}

yapollo.as 代码:

package {
public class yapollo{
private var $_name:string =”yapollo”;
public var $_num:number =0;
public function yapollo():void{
trace($_name);

}
public function secondfunc():void{

$_num++;
trace(”this a called function $_num::”+$_num);

}

}
}

测试实例

var uml1:youmila = new youmila();
var uml2 = cloneobject(uml1);
trace(”类型”+getqualifiedclassname(uml2));
输出结果:

youmila
类型object
原来的对象类型丢失了,所以对于对象而言,四行不够,必须
用registerclassalias来保存类的别名,以用于丢失后恢复类的类型
测试实例

var uml1:youmila = new youmila();

var uml2 = cloneobject(uml1);
trace(”类型”+getqualifiedclassname(uml2));

var apollo:yapollo = new yapollo();

apollo.secondfunc();
var apollo2 = cloneobject(apollo);
trace(”第一次输出复制对象的$_num值”+apollo2.$_num);
trace(”类型”+getqualifiedclassname(apollo2));

apollo2.secondfunc();
trace(”第二次输出复制对象的$_num值”+apollo2.$_num);

输出结果:

youmila
输出类的结构src::youmila
类的名称src
[class youmila]
youmila
类型src::youmila
yapollo
this a called function $_num::1
输出类的结构yapollo
类的名称yapollo
[class yapollo]
yapollo
第一次输出复制对象的$_num值1
类型yapollo
this a called function $_num::2
第二次输出复制对象的$_num值2