Haxe - 将枚举作为标志发送到函数

时间:2013-05-16 06:10:44

标签: enums flags haxe enum-flags nme

我只是想将我的代码从C#转换为Haxe NME。我使用枚举作为标志。

[Flags]
enum State
{
    StateOne    = 1,
    StateTwo    = 2,
    StateThree  = 4
}

并使用它

if (someObj.HasState(State.StateOne | State.StateTwo))
{
    // Contains both the states. Do something now.
}

我不知道如何在Haxe NME中这样做。

感谢。

2 个答案:

答案 0 :(得分:12)

在Haxe 3中,有haxe.EnumFlags。这使用了Haxe 3 Abstract Types,它基本上包装了一个底层类型,在这种情况下,它使用了Int,就像你已经完成的那样 - 但是它将它包装在一个漂亮的API中,所以你不必担心细节。

以下是一些示例代码:

import haxe.EnumFlags;

class EnumFlagTest 
{
    static function main()
    {
        var flags = new EnumFlags<State>();
        flags.set(StateOne);
        flags.set(StateTwo);
        flags.set(StateThree);
        flags.unset(StateTwo);

        if (flags.has(StateOne)) trace ("State One active");
        if (flags.has(StateTwo)) trace ("State Two active");
        if (flags.has(StateThree)) trace ("State Three active");

        if (flags.has(StateOne) && flags.has(StateTwo)) trace ("One and Two both active");
        if (flags.has(StateOne) && flags.has(StateThree)) trace ("One and Three both active");
    }
}

enum State
{
    StateOne;
    StateTwo;
    StateThree;
}

所有这些工作都存储为标准Int,并使用像你所做的整数运算符,因此它应该非常快(不包装在外部对象中)。如果您想在框下查看它的工作原理,可以查看EnumFlags的源代码here

如果你还在使用Haxe 2,那么你可以创建一个非常相似的对象,当然,它必须创建一个对象以及整数,所以如果你做了数千(数百万?)然后你可能会慢下来。等效代码,应该与Haxe 2一起使用(虽然我没有检查过):

class MyEnumFlags<T:EnumValue>
{
    var i:Int;

    public function new(?i=0)
    {
        this.i = i;
    }

    public inline function has( v : T ) : Bool {
        return i & (1 << Type.enumIndex(v)) != 0;
    }

    public inline function set( v : T ) : Void {
        i |= 1 << Type.enumIndex(v);
    }

    public inline function unset( v : T ) : Void {
        i &= 0xFFFFFFF - (1 << Type.enumIndex(v));
    }

    public inline static function ofInt<T:EnumValue>( i : Int ) : MyEnumFlags<T> {
        return new MyEnumFlags<T>(i);
    }

    public inline function toInt() : Int {
        return i;
    }
}

答案 1 :(得分:1)

我找到了它。我在使用枚举时遇到了麻烦,但我成功地使用了常量。这是我使用的简单测试文件。

package ;

class FlagsTest
{

    static inline var FLG_1:Int = 1;
    static inline var FLG_2:Int = 2;

    public static function main() : Void
    {
        var flag:Int = FLG_1;
        if (hasFlag(flag, FLG_1))
        {
            trace ("Test 1 passed");
        }
        flag |= FLG_2;
        if (hasFlag(flag, FLG_2))
        {
            trace ("Test 2 passed");
        }
    }

    public static function hasFlag( flags:Int, flag:Int ) : Bool
    {
        return ((flags & flag) == flag) ? true : false;
    }

}

输出:

FlagsTest.hx line 14: Test 1 passed
FlagsTest.hx line 19: Test 2 passed
相关问题