检查不带参数的枚举

Check equaling enum without parameter

我使用枚举,但找不到检查均衡的好方法。

enum Turn {
    A(value:Int);
    B(value:Int);
}
class Test {
    static function main() {
        var turn = Turn.A(100);
        //I want to Check turn is Turn.A(any value) without using 'switch'.
        if (turn == Turn.A) ...
    }
}

有什么好的简单的检查方法吗?

您可以使用 .match() function:

if (turn.match(Turn.A(_)))

我还没有测试过,但使用类型 class:

可能会更快
if (Type.enumConstructor(turn) == "A") ...

因为它不安全("A" 可能是错字),我建议使用 ExprTools:

import haxe.macro.ExprTools.*;
if (Type.enumConstructor(turn) == toString(macro A)) ...

还有另一种方法,但我不认为它更快:

if (Type.enumIndex(turn) == Type.enumIndex(A(0))) ...

您可能会针对不同的枚举将条件评估为真:

enum Color { Red; }
if (Type.enumIndex(turn) == Type.enumIndex(Red)) ... // true