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

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

    • Flags are used when an enumerable value represents a collection of enum members.

    • here we use bitwise operators, | and &

    • Example

                   [Flags]
                   public enum Sides { Left=0, Right=1, Top=2, Bottom=3 }
      
                   Sides leftRight = Sides.Left | Sides.Right;
                   Console.WriteLine (leftRight);//Left, Right
      
                   string stringValue = leftRight.ToString();
                   Console.WriteLine (stringValue);//Left, Right
      
                   Sides s = Sides.Left;
                   s |= Sides.Right;
                   Console.WriteLine (s);//Left, Right
      
                   s ^= Sides.Right; // Toggles Sides.Right
                   Console.WriteLine (s); //Left
      

提交回复
热议问题