问题
I'd like to look for a specific class type into an array. No clue how.
var a:A = new A();
var b:B = new B(); // B extends A
var c:C = new C(); // C extends A
var arr:Array<A> = [];
arr.push(a);
arr.push(b);
arr.push(c);
// i'd like something like:
c = arr.get<C>();
回答1:
In Haxe, like Java, you can't get access to the type parameter inside the code, since in most implementations it is erased, meaning the same as "Dynamic". This means that in order to implement that, you'd need a function like this:
public static function getWithType<T>(array:Array<Dynamic>, cl:Class<T>):Null<T>
{
for (el in array)
{
if (Std.is(el, cl))
return el;
}
return null;
}
Note that you need to pass the "Class" argument. You would use it like this:
c = MyClass.getWithType(arr, C);
You can also use the 'using' statement so you can use it like this:
using MyClass;
(...)
c = arr.getWithType(C);
You can also achieve a similar behavior with the Lambda class:
using Lambda;
c = arr.filter(function(el) return Std.is(el, C)).first();
回答2:
Look at mixins, you can write your own function that will check elements types and return their.
来源:https://stackoverflow.com/questions/11588011/how-to-look-for-a-class-type-in-an-array-using-generics