AS3 - 克隆对象 [英] AS3 - Clone an object

查看:374
本文介绍了AS3 - 克隆对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个游戏多种船型。我的船舶类有一个静态数组抱在一起在它的类型中的一种。每当我提出一个新的船舶(除初始化这个数组的时候),我希望把它的一个克隆现有的船舶在我的原型数组对象。

I have a game with a variety of ship types. My Ship class has a static array holding one of each of the types in it. Whenever I make a new Ship (other than when initializing this array), I want to make it a clone of one of the existing Ship objects in my prototype array.

1 - 我怎样才能通过所有属性在一个船舶目标运行,并将其分配给第二个船舶反对呢?

1 - How can I run through all the properties in one Ship object and assign them to a second Ship object?

2 - 我怎么可以看到,如果一个属性是一个对象或基本类型如字符串 INT ?一些在我的船舶类需要对象被克隆,有的只是需要保持同样的参考。

2 - How can I see if a property is an object or a basic type like String or int? Some of the objects in my Ship class need to be cloned, and some are just references that need to stay the same.

推荐答案

一种选择,可以说是最敏捷的,是定义的克隆方法,你需要克隆每个类,如:

One option, arguably the most agile, would be to define clone methods for each class that you need to clone, such as:

class Ship
{
    public var prop1:Number;
    public var otherClassInstance:OtherClass;
    public function clone():Ship
    {
        var result:Ship = new Ship();
        result.prop1 = this.prop1;
        result.otherClassInstance = this.otherClassInstance.clone()
    }
}

class OtherClass
{
    public var prop1:Number;
    public function clone():OtherClass
    {
        var result:OtherClass = new OtherClass();
        result.prop1 = this.prop1;
    }
}

另一种选择是使用ByteArray类像这个例子从Adobe的文档,以克隆对象:

Another option is to clone an object by using the ByteArray class like this example from the Adobe documentation:

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

我见过的情况下这种方法不适用于自定义类的克隆实例的工作,尤其是视图类,如精灵。

I've seen instances where this approach does not work for cloning instances of custom classes, specifically view classes like Sprites.

另一种方法是使用不如describeType flash.utils 包。随着不如describeType 您可以通过对象的属性迭代。

Another approach is to use describeType from the flash.utils package. With describeType you can iterate through the properties of an object.

下面是一个使用不如describeType 来检查一个对象的属性是的<一个部分的示例href="https://github.com/makemachine/makemachine.actionscript/blob/master/src/makemachine/utils/introspect.as">utils LIB 我写的。

Here is an example of using describeType to inspect the properties of an object that is a part of a utils lib I wrote.

至于检查属性的类型,你可以使用不如describeType 或者你也可以使用运营商像这样的:

As for checking the type of the property, you can use describeType or you can also use the is operator like this:

if( myObj is SomeClass )
{

}

if( myObj is OtherClass )
{

}

这篇关于AS3 - 克隆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆