2009-02-19 123 views
8

我想克隆一個Canvas對象,其中包含具有多個幾何形狀的Degrafa曲面。如何在Flex中克隆對象?

我嘗試了天真的做法:

return ObjectUtil.copy(graph_area) as Canvas; 

這就造成了錯誤:

TypeError: Error #1034: Type Coercion failed: cannot convert [email protected] to com.degrafa.geometry.Geometry. 
TypeError: Error #1034: Type Coercion failed: cannot convert [email protected] to com.degrafa.geometry.Geometry. 
TypeError: Error #1009: Cannot access a property or method of a null object reference. 
    at mx.core::Container/addChildAt()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\Container.as:2196] 
    at mx.core::Container/addChild()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\Container.as:2140] ... 

回答

9

你想被稱爲深拷貝什麼,產生一個新的實例與原來相同的信息。

我知道它是如何使用的ByteArray如下做的唯一方法:

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

AS3真是個缺乏Object.clone()...

+2

如果你看一下ObjectUtil.copy()的來源,它完全一樣。 – 2010-04-02 14:35:36

+0

是的,它使用AMF來序列化和反序列化對象。 – LiraNuna 2010-04-02 23:11:46

+0

我在此代碼中出錯...錯誤:錯誤#2030:遇到文件結尾。 \t at flash.utils :: ByteArray/readObject() – Devendra 2013-01-23 10:20:09

0

我不認爲ObjectUtil.copy將用於克隆畫布。 根據flex文檔:

複製 此方法專用於複製數據對象,如集合的元素。它不適用於複製UIComponent對象,如TextInput控件。如果要創建特定UIComponent對象的副本,則可以創建組件的子類並實現clone()方法或其他方法來執行副本。

1

我發現自己想要的東西更多類似這樣的唉它似乎仍然沒有複製一個TextArea(又名UI對象)...

public function duplicateObject(sourceObject:*, targetObject:*):void { 
    var buffer:ByteArray = new ByteArray(); 
    buffer.writeObject(sourceObject); 
    buffer.position = 0; 
    targetObject = buffer.readObject(); 
} 
1

我得到了同樣的問題(對於NamedEntity界面我創建),在這裏尋找答案,但只有在調用registerClassAlias方法(我從http://richapps.de/?p=34中獲得)的時候纔開始工作。就這樣:

public static function clone(namedEntity:NamedEntity):NamedEntity { 
registerClassAlias('test',ReflectionUtil.classByObject(namedEntity)); 
var returnObject:NamedEntity = ObjectUtil.copy(namedEntity) as NamedEntity; 
} 
7

ObjectUtil

靜態方法ObjectUtil.copy()是AS3的 「Object.clone()」:

public static function copy(value:Object):Object 

Copies the specified Object and returns a reference to the copy. The copy is made using a native serialization technique. This means that custom serialization will be respected during the copy.

This method is designed for copying data objects, such as elements of a collection. It is not intended for copying a UIComponent object, such as a TextInput control. If you want to create copies of specific UIComponent objects, you can create a subclass of the component and implement a clone() method, or other method to perform the copy.