How do you pass multiple enum values in C#?

后端 未结 10 1911
灰色年华
灰色年华 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 16:53

    [Flags]
        public enum DaysOfWeek{
    
    
            Sunday = 1 << 0,
            Monday = 1 << 1,
            Tuesday = 1 << 2,
            Wednesday = 1 << 3,
            Thursday = 1 << 4,
            Friday =  1 << 5,
            Saturday =  1 << 6
        }
    

    call the method in this format

    MethodName(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);

    Implement a EnumToArray method to get the options passed

    private static void AddEntryToList(DaysOfWeek days, DaysOfWeek match, List dayList, string entryText) {
                if ((days& match) != 0) {
                    dayList.Add(entryText);
                }
            }
    
            internal static string[] EnumToArray(DaysOfWeek days) {
                List verbList = new List();
    
                AddEntryToList(days, HttpVerbs.Sunday, dayList, "Sunday");
                AddEntryToList(days, HttpVerbs.Monday , dayList, "Monday ");
                ...
    
                return dayList.ToArray();
            }
    

提交回复
热议问题