2011-05-09 66 views
1

我想克隆一個類對象。我試圖從here如下:AS3 - 類具有參數化構造函數時的克隆類對象

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

    public class MyClass 
    { 
     public var property1:String; 
     public var property2:Array; 

     public function clone():MyClass 
     { 
      registerClassAlias("MyClass", MyClass); 

      var bytes:ByteArray = new ByteArray(); 
      bytes.writeObject(this); 
      bytes.position = 0; 

      return bytes.readObject() as MyClass; 
     } 
    } 
} 

但這只是工作的時候班裏有一個默認的構造函數,而不是當它參數的構造函數:

如何克隆一個類對象時,類有任何想法,參數化的構造函數?

問候

回答

2

這是最好的,我可以爲你做:

package 
{ 

    import flash.display.Sprite; 


    public class Thing extends Sprite 
    { 

     // Cloneable properties. 
     private var _cloneable:Array = ["x","y","val1","val2"]; 


     // Properties. 
     public var val1:uint = 10; 
     public var val2:String = "ten"; 


     /** 
     * Returns a new Thing with the same properties. 
     */ 
     public function clone():Thing 
     { 
      var t:Thing = new Thing(); 

      for each(var i:String in _cloneable) 
      { 
       t[i] = this[i]; 
      } 

      return t; 
     } 

    } 

} 

所有你需要做的就是添加你想有克隆能夠_cloneable

示例使用屬性:

var thing:Thing = new Thing(); 

thing.x = 15; 
thing.y = 10; 
thing.val1 = 25; 
thing.val2 = "twentyfive"; 

// Clone initial Thing. 
var thing2:Thing = thing.clone(); 

trace(thing2.x, thing2.y, thing2.val1, thing2.val2); // 15 10 25 twentyfive 
+0

感謝您的幫助。問候 – user427969 2011-05-12 05:35:03

0

我的建議是不要讓它太複雜d而不是在想事情。實際上沒有必要做比這更復雜的事情。

public function clone():Thing { 
    var t:Thing = new Thing(); 

    t.x = this.x; 
    t.y = this.y; 
    t.val1 = this.val1; 
    t.val2 = this.val2; 

    return t; 
} 

如果你在你的構造函數中有一個參數。

public function Thing(x:int,y:int) { 
    this.x = x; 
    this.y = y; 
} 

public function clone():Thing { 
    var t:Thing = new Thing(this.x, this.y); 

    t.val1 = this.val1; 
    t.val2 = this.val2; 

    return t; 
} 

我喜歡其他答案,它很聰明,但很多隻是設置一些屬性的流失。不要過度考慮問題。

0

您可以創建一個具有可選參數的構造函數的類。從測試驅動開發和性能點來看,這是一個很好的做法。

相關問題