How to look for a class type in an array using generics

元气小坏坏 提交于 2019-12-11 04:22:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!