测试在Flags Enum中仅设置一位 [英] Test that only a single bit is set in Flags Enum
本文介绍了测试在Flags Enum中仅设置一位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个标记Enum
So I have a flags Enum
public Enum test
{
test1 = 1,
test2 = 2,
test3 = 4,
etc.
}
如何测试这一位,并且只设置了一位?
How can I test that one bit, and only one bit is set?
我以前已经100%完成了此操作,但是我现在的脑子没用!
I've 100% done this before but my mind is not working this am!
推荐答案
要检查数字中是否只设置了一位,数字(根据定义)必须为2的幂.因此,您可以使用以下内容进行测试:
To check that only a single bit is set in a number, the number must (by definition) be a power of two. As such, you can use the following to test:
int intVal = ((int)myEnumFlags);
bool singleBitIsSet = intVal != 0 && (intVal & (intVal-1)) == 0;
我最喜欢的这类东西参考:
My favorite reference for this kind of thing:
这篇关于测试在Flags Enum中仅设置一位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文