How do you pass multiple enum values in C#?

后端 未结 10 1888
灰色年华
灰色年华 2020-11-29 16:50

Sometimes when reading others\' C# code I see a method that will accept multiple enum values in a single parameter. I always thought it was kind of neat, but never looked in

10条回答
  •  粉色の甜心
    2020-11-29 17:02

    Mark your enum with the [Flags] attribute. Also ensure that all of your values are mutually exclusive (two values can't add up to equal another) like 1,2,4,8,16,32,64 in your case

    [Flags]
    public enum DayOfWeek
    { 
    Sunday = 1,   
    Monday = 2,   
    Tuesday = 4,   
    Wednesday = 8,   
    Thursday = 16,   
    Friday = 32,    
    Saturday = 64
    }
    

    When you have a method that accepts a DayOfWeek enum use the bitwise or operator (|) to use multiple members together. For example:

    MyMethod(DayOfWeek.Sunday|DayOfWeek.Tuesday|DayOfWeek.Friday)
    

    To check if the parameter contains a specific member, use the bitwise and operator (&) with the member you are checking for.

    if(arg & DayOfWeek.Sunday == DayOfWeek.Sunday)
    Console.WriteLine("Contains Sunday");
    

提交回复
热议问题