Pro*_*mer 2 c# enums bitwise-operators
我有颜色选择enum,代表红色,蓝色,绿色和无.
[Flags]
public enum SelectedColor
{
None, Red, Blue, Green
}
Run Code Online (Sandbox Code Playgroud)
当我创建一个新的枚举并将其设置为Red和Green,然后检查是否Blue设置,则返回true. Blue从未在任何地方设置.
例如:
SelectedColor selectedColor = SelectedColor.Red;
selectedColor |= SelectedColor.Green; //Add Green to Selection
//Check if blue is set
Debug.Log("Blue Selected hasFlag? : " + hasFlag(selectedColor, SelectedColor.Blue));
//Check if blue is set
Debug.Log("Blue Selected isSet? : " + isSet(selectedColor, SelectedColor.Blue));
Run Code Online (Sandbox Code Playgroud)
输出:
Blue Selected hasFlag?:错
Blue Selected isSet?:是的
hasFlag和isSet函数:
bool hasFlag(SelectedColor source, SelectedColor value)
{
int s1 = (int)source;
return Convert.ToBoolean((s1 & Convert.ToInt32(((int)value) == s1)));
}
bool isSet(SelectedColor source, SelectedColor critValue)
{
//return ((source & critValue) == critValue);
return ((source & critValue) != 0);
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我的isSet函数返回了错误的值.我曾经尝试都return ((source & critValue) == critValue)和return ((source & critValue) != 0);它,但他们都还是失败了.这应该根据我对SO和这篇文章的研究.
我的hasFlag功能很好,但为什么isSet函数返回错误的值?
请注意我使用的是.NET 3.5,所以我不能使用.NET 4枚举辅助函数,例如HasFlag.
如果您没有为枚举指定值,则会将序号分配给它们,如下所示:
[Flags]
public enum SelectedColor // WRONG
{
None = 0, // 000
Red = 1, // 001
Blue = 2, // 010
Green = 3 // 011 <-- Not the next power of two!
}
Run Code Online (Sandbox Code Playgroud)
然后这发生了:
selectedColor = SelectedColor.Red; // 001
selectedColor |= SelectedColor.Green; // (001 | 011 ) == 011, which is still Green
Run Code Online (Sandbox Code Playgroud)
您需要为[Flags]枚举使用2的幂,如下所示:
[Flags]
public enum SelectedColor // CORRECT
{
None = 0, // 000
Red = 1, // 001
Blue = 2, // 010
Green = 4 // 100
}
Run Code Online (Sandbox Code Playgroud)
然后它正常工作:
selectedColor = SelectedColor.Red; // 001
selectedColor |= SelectedColor.Green; // (001 | 100) == 101, which is Red, Green
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
279 次 |
| 最近记录: |