سؤال

Is it possible to cast a variable to another type based on information available at runtime?

If I have:

interface Foo
{
}

class Bar implements Foo
{
    public function new()
    {
    }
}

I want to do something like this (method is simplified for clarity):

public static function dynamicCast<T : Foo>(target : Foo, cls : Class<T>) : T
{
    var ret : T = cast(pTarget, cls);
    return ret;
}

I get the following compiler error:

Unexpected )
هل كانت مفيدة؟

المحلول

I found the answer in the official haxe documentation. Here it is:

public static function dynamicCast<T : Foo>(target : Foo, cls : Class<T>) : T
{
    if(Std.is(target, cls))
    {
        var ret : T = cast target;
        return ret;
    }
    return null;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top