我有一個基本的原型類:如何在通用函數中轉換爲動態類型?
class CItemProto {
public var id:Int;
public var count:Int;
...
}
和別樣的一些擴展:
class CItemThing extends CItemProto { ... }
class CItemResource extends CItemProto { ... }
class CItemRecipe extends CItemProto { ... }
...等等。項目的每個實例都具有唯一的ID,這樣我就可以在一個清單類存儲我所有的東西用簡單的IntMap訪問:
class CInventory {
var mMap:IntMap<CItemProto>;
public function new() {
mMap = new IntMap();
}
public inline function set(item:CItemProto) { mMap.set(item.id, item); }
public function get<T:CItemProto>(id:Int):T {
var item = mMap.get(aId);
if (Std.is(item, Class<T>)) // it doesn't work saying Unexpected)
return cast item;
return null;
}
}
我的觀點是使用的get()訪問一些項目編號以及此項目類型如果我在選擇類型時出錯,方法應該返回null值。例如:
// should return instance of CItemThing if it exists or null in the other way
var thing:CItemThing = inventory.get(123);
但它不起作用。如果我要求錯誤類型,安全投出要求,簡單不安全的投射失敗動態類型代替通用T替代。我應該怎麼做才能根據其類型過濾請求的項目?因爲我可以通過類型作爲第二個參數,但它看起來很笨重和過度。
UPDATE我找到了主題How to look for a class type in an array using generics所以我的問題沒有意義。我將通過所需的類型作爲第二個參數。
謝謝,我已經做出了相同的解決方案。現在我看到,將類作爲預期數據的類型傳遞並不是什麼缺點。 – meps
你可以使用'return Std.instance(v,c)'來代替'if..return cast ... return null' – KevinResoL