How do you pass multiple enum values in C#?

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

    In my particular situation, I would like to use the System.DayOfWeek

    You can not use the System.DayOfWeek as a [Flags] enumeration because you have no control over it. If you wish to have a method that accepts multiple DayOfWeek then you will have to use the params keyword

    void SetDays(params DayOfWeek[] daysToSet)
    {
        if (daysToSet == null || !daysToSet.Any())
            throw new ArgumentNullException("daysToSet");
    
        foreach (DayOfWeek day in daysToSet)
        {
            // if( day == DayOfWeek.Monday ) etc ....
        }
    }
    
    SetDays( DayOfWeek.Monday, DayOfWeek.Sunday );
    

    Otherwise you can create your own [Flags] enumeration as outlined by numerous other responders and use bitwise comparisons.

提交回复
热议问题