Sri*_*ati 6 enums flags haxe enum-flags nme
我只是想将我的代码从C#转换为Haxe NME.我使用枚举作为标志.
[Flags]
enum State
{
StateOne = 1,
StateTwo = 2,
StateThree = 4
}
Run Code Online (Sandbox Code Playgroud)
并使用它
if (someObj.HasState(State.StateOne | State.StateTwo))
{
// Contains both the states. Do something now.
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何在Haxe NME中这样做.
谢谢.
Jas*_*eil 13
在Haxe 3中,有haxe.EnumFlags.这使用Haxe 3 抽象类型,它基本上包装了一个底层类型,在这种情况下,它使用一个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;
}
Run Code Online (Sandbox Code Playgroud)
所有这些工作都存储为标准的Int,并使用像你所做的整数运算符,因此它应该非常快(不包装在外部对象中).如果你想看看它在框下是如何工作的,可以在这里查看EnumFlags的源代码.
如果你仍然在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;
}
}
Run Code Online (Sandbox Code Playgroud)
我已经设法找到它了。我在使用枚举时遇到了麻烦,但我在使用常量方面取得了成功。这是我使用的简单测试文件。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
FlagsTest.hx line 14: Test 1 passed
FlagsTest.hx line 19: Test 2 passed
Run Code Online (Sandbox Code Playgroud)