Bit智能操作符如何与Enums一起使用

时间:2016-08-10 06:36:44

标签: c# .net enums

enum WeekDays
{
    Monday = 0,
    Tuesday = 1,
    Wednesday = 2,
    Thursday = 3,
    Friday = 4,
    Saturday = 5,
    Sunday = 6
}

private void button4_Click(object sender, EventArgs e)
{
    WeekDays days0 = WeekDays.Monday | WeekDays.Tuesday | WeekDays.Wednesday;

    WeekDays days1 = WeekDays.Monday | WeekDays.Tuesday | WeekDays.Wednesday | WeekDays.Thursday;

    WeekDays days2 = WeekDays.Monday | WeekDays.Tuesday | WeekDays.Wednesday | WeekDays.Thursday | WeekDays.Friday;
}

输出是:

days0 = Thursday,
days1 = Thursday,
days2 = 7

有人可以解释这是如何工作的逻辑吗?

2 个答案:

答案 0 :(得分:11)

基本上,您的枚举不适合按位操作使用。为了适合按位运算,每个不同的值应该由不同的位表示 - 而你只是得到数字0-6。

您获得输出的原因是:

  • days00 | 1 | 2,即3,Thursday
  • 的值
  • days10 | 1 | 2 | 3,仍为3,Thursday
  • 的值
  • days20 | 1 | 2 | 3 | 4,即7,这不是您枚举中的命名值

为了使你的枚举适合于按位运算,你应该这样声明:

[Flags] // Affects string parsing and formatting
enum BitwiseWeekDays
{
    None = 0,
    Monday = 1 << 0,
    Tuesday = 1 << 1,
    Wednesday = 1 << 2,
    Thursday = 1 << 3,
    Friday = 1 << 4,
    Saturday = 1 << 5,
    Sunday = 1 << 6
}

现在每个值都由一个单独的位表示,因此您可以&#34;或&#34;他们在一起将它们结合起来。

答案 1 :(得分:4)

0 | 1 | 2 = (bitwise  00 | 01 | 10 = 11 ) = 3
0 | 1 | 2 | 3 = (bitwise  00 | 01 | 10 | 11 = 11 ) = 3
0 | 1 | 2 | 3 | 4 = (bitwise  000 | 001 | 010 | 011 | 100 = 111 ) = 7