How do you pass multiple enum values in C#?

后端 未结 10 1899
灰色年华
灰色年华 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

    I think the more elegant solution is to use HasFlag():

        [Flags]
        public enum DaysOfWeek
        {
            Sunday = 1,
            Monday = 2,
            Tuesday = 4,
            Wednesday = 8,
            Thursday = 16,
            Friday = 32,
            Saturday = 64
        }
    
        public void RunOnDays(DaysOfWeek days)
        {
            bool isTuesdaySet = days.HasFlag(DaysOfWeek.Tuesday);
    
            if (isTuesdaySet)
            {
                //...
            }
        }
    
        public void CallMethodWithTuesdayAndThursday()
        {
            RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
        }
    

提交回复
热议问题