The usage of Flags in C#'s Enum

The Flags keyword allows us to use multiple combined values ​​when using .net enum variables

Designed in advance in the project, it is very convenient to use

Copy an example online

[Flags]
    enum WeekDays
    {
        // Note: Do not set Sunday to 0x0 here, as for why it is left to everyone to think about 
        Monday = 0x1 ,
        Tuesday = 0x2,
        Wednesday = 0x4,
        Thursday = 0x8,
        Friday = 0x10,
        Saturday = 0x20,
        Sunday = 0x40
    }
static  void TestEnumFlags()
        {
            /* ***********Kingmoon Lab's enum flags syntax ******************** */ 
            /* Use '|' You can separate the values ​​*/ 
            WeekDays wds = WeekDays.Monday | WeekDays.Sunday | WeekDays.Tuesday;
            Console.WriteLine( " I'm coming to my aunt in 3 days: " + wds);
             /* Let's take a look at the calculation process:
             * OR operation:
                 0000 0001 -- Monday 0x1
              or 0100 0000 -- Saturday 0x20
              or 0000 0010 -- Tuesday 0x2
             =   0100 0011 = 67
             *In other words: a bit is 1 means that the value on this bit exists in the enumeration
             */ 
            Console.WriteLine( " The 3-day combination of Int is: " +( int )wds);
             /* It is easy to use the above rules to determine whether an enumeration value contains an enumeration value */ 
            if ((wds & WeekDays .Monday) != 0 )
                Console.WriteLine( " Monday is one of the days " );
             if ((wds & WeekDays.Saturday) == 0 )
                Console.WriteLine( " Saturday is not one of the days " );

            // (Supplementary) If you remove a value, you can use this method as the original 
            /* remove Monday from the enumeration variable
             *  0100 0011
             * &1011 1111 (~WeekDays.Monday) negated
             * =0000 0011 This removes Monday!
            */
            wds = wds & (~WeekDays.Monday);
            Console.WriteLine( " Remove Monday effect: " + wds);
        }

result

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325017399&siteId=291194637