2014-02-26 34 views
2
public dynamic class TypedDictionary extends Dictionary { 
    private var _type:Class; 

    public function TypedDictionary(type:Class, weakKeys:Boolean = false) { 
     _type = type; 
     super(weakKeys); 
    } 

    public function addValue(key:Object, value:_type):void { 
     this[key] = value; 
    } 

    public function getValue(key:Object):_type{ 
     return this[key]; 
    } 
... 

我想使TypedDictionary具有類型化。但我不能在addValuegetValue中使用_type。這個想法是使用下一個構造:AS3 TypedDictionary?

var td:TypedDictionary = new TypedDictionary(myClass, true); 
td.addValue("first", new myClass()); 
... 
var item:myClass = td.getValue("first"); 
item.someFunction(); 

是否有使用動態類類型的能力?

回答

1

如果我理解你所要求的。
這是未經測試的代碼,所以它可能容易出錯,但它應該讓你走上正確的道路。

public dynamic class TypedDictionary extends Dictionary { 
    private var _type:Class; 

    public function TypedDictionary(type:String, weakKeys:Boolean = false) { 
     _type = getDefinitionByName(type) as Class; 
     super(weakKeys); 
    } 

    public function addValue(key:Object, value:*):void { 
     if(_type == getDefinitionByName(getQualifiedClassName(value))){ 
      this[key] = value; 
     }else{ 
      trace('failed type match') 
     } 
    } 

    public function getValue(key:Object):*{ 
     return this[key]; 
    } 
... 


var td:TypedDictionary = new TypedDictionary("com.somepackage.myClass", true); 
td.addValue("first", new myClass()); 

var item:myClass = td.getValue("first"); 
item.someFunction(); 
+0

有趣。怎麼樣getValue(key:Object):'_type'? –

+0

啊我錯過了。現在全部修好了 –