我個人認爲這是好的,只要因爲你完全確定你正在鑄造到正確的類型 - 我見過其他一些Haxe庫(如minject)使用這種方法。
隨着HAXE,您可以使用類型參數,如下所示:
var c:Map<String,BaseComponent>;
public function getComponent<T:BaseComponent>(name:String, type:Class<T>):T {
if (components.exists(name)) {
var c = components[name];
if (Std.is(c, type)) {
return cast c;
}
}
return null; // the component with that name didn't exist, or was the wrong type
}
這樣您的使用情況可以是:
var transform = componentManager.getComponent("transform", TransformComponent);
if (transform!=null) {
transform.doSomething();
}
在這種情況下,轉換將全部輸入爲「TransformComponent」編譯器會讓你訪問它的所有方法等。
最後,如果你只有一個組件的每個類型的實例,你可以更容易:
public function addComponent<T:BaseComponent>(component:T) {
var type = Type.getClass(component);
var name = Type.getClassName(type);
components[name] = component;
}
public function getComponent<T:BaseComponent>(type:Class<T>):T {
var name = Type.getClassName(type);
return cast components[name]; // Either the component with the correct type name, or null.
}
componentManager.addComponent(new TransformComponent());
var t = componentManager.get(TransformComponent);
$type(t); // TransformComponent, it is correctly typed
真棒:)多數民衆贊成正是我想知道,和仿製藥使它更清潔...謝謝 – Nico
我想我會把這兩種方法爲方便 – Nico
只是讓我明白這一點完全地,如果沒有第二個參數或指定的類型,投射如何工作,例如,我可以理解:var i:Int =投射myfloat,但它如何在沒有指定類型的情況下工作? – Nico