如何使用按位&(和)来实现这个?

这个问题在这里已经有了答案:

  • 在C#中,[Flags]枚举属性意味着什么? 10个答案

  • 测试位标志的典型模式是

    // Entire key match  
    if (returned_value & value_to_test == value_to_test) {
      ...
    }
    
    // Partial key match  
    if (returned_value & value_to_test != 0) {
      ...
    }
    

    例如,如果你想测试3号口袋是否满了:

    if (returned_value & POCKET.P3_FULL == POCKET.P3_FULL) {
      ...
    }
    

    您可以通过|组合标志 并测试这种组合标志的部分匹配:

    const int ALL_ARE_FULL = POCKET.P1_FULL | POCKET.P2_FULL | POCKET.P3_FULL;
    
    ...
    
    // Test if any part of the flag is match (i.e. any pocket - at least one - is full)
    // Please, notice != 0 comparison
    if (returned_value & ALL_ARE_FULL != 0) {
       ...
    }
    
    // Compare with this: all three pockets are full
    if (returned_value & ALL_ARE_FULL == ALL_ARE_FULL) {
       ...
    }
    
    链接地址: http://www.djcxy.com/p/54445.html

    上一篇: How to implement this using the bitwise & (and)?

    下一篇: C# flags vs sample enums