【发布时间】:2016-06-09 21:44:34
【问题描述】:
我有一个基本的原型类:
class CItemProto {
public var id:Int;
public var count:Int;
...
}
以及一些不同类型的扩展:
class CItemThing extends CItemProto { ... }
class CItemResource extends CItemProto { ... }
class CItemRecipe extends CItemProto { ... }
...等等。每个 item 实例都有唯一的 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() 访问器和一些项目 id 和这个项目类型,如果我在类型选择中出错,方法应该返回 null 值。例如:
// should return instance of CItemThing if it exists or null in the other way
var thing:CItemThing = inventory.get(123);
但它不起作用。如果我请求错误的类型,简单的不安全转换会失败,安全转换需要 Dynamic 类型而不是通用 T 替换。我应该怎么做才能按类型过滤请求的项目?当然,我可以将类型作为第二个参数传递,但它看起来庞大且过多。
更新我找到了主题How to look for a class type in an array using generics,所以我的问题毫无意义。我将传递所需的类型作为第二个参数。
【问题讨论】: