What does the [Flags] Enum Attribute mean in C#?

前端 未结 13 2225
慢半拍i
慢半拍i 2020-11-21 04:21

From time to time I see an enum like the following:

[Flags]
public enum Options 
{
    None    = 0,
    Option1 = 1,
    Option2 = 2,
    Option3 = 4,
    Op         


        
13条回答
  •  孤街浪徒
    2020-11-21 04:56

    There's something overly verbose to me about the if ((x & y) == y)... construct, especially if x AND y are both compound sets of flags and you only want to know if there's any overlap.

    In this case, all you really need to know is if there's a non-zero value[1] after you've bitmasked.

    [1] See Jaime's comment. If we were authentically bitmasking, we'd only need to check that the result was positive. But since enums can be negative, even, strangely, when combined with the [Flags] attribute, it's defensive to code for != 0 rather than > 0.

    Building off of @andnil's setup...

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace BitFlagPlay
    {
        class Program
        {
            [Flags]
            public enum MyColor
            {
                Yellow = 0x01,
                Green = 0x02,
                Red = 0x04,
                Blue = 0x08
            }
    
            static void Main(string[] args)
            {
                var myColor = MyColor.Yellow | MyColor.Blue;
                var acceptableColors = MyColor.Yellow | MyColor.Red;
    
                Console.WriteLine((myColor & MyColor.Blue) != 0);     // True
                Console.WriteLine((myColor & MyColor.Red) != 0);      // False                
                Console.WriteLine((myColor & acceptableColors) != 0); // True
                // ... though only Yellow is shared.
    
                Console.WriteLine((myColor & MyColor.Green) != 0);    // Wait a minute... ;^D
    
                Console.Read();
            }
        }
    }
    

提交回复
热议问题