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

前端 未结 13 2224
慢半拍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:58

    Please see the following for an example which shows the declaration and potential usage:

    namespace Flags
    {
        class Program
        {
            [Flags]
            public enum MyFlags : short
            {
                Foo = 0x1,
                Bar = 0x2,
                Baz = 0x4
            }
    
            static void Main(string[] args)
            {
                MyFlags fooBar = MyFlags.Foo | MyFlags.Bar;
    
                if ((fooBar & MyFlags.Foo) == MyFlags.Foo)
                {
                    Console.WriteLine("Item has Foo flag set");
                }
            }
        }
    }
    

提交回复
热议问题