How do you pass multiple enum values in C#?

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

    With the help of the posted answers and these:

    1. FlagsAttribute Class (Look at the comparison of using and not using the [Flags] attribute)
    2. Enum Flags Attribute

    I feel like I understand it pretty well.

    Thanks.

    0 讨论(0)
  • 2020-11-29 17:16

    I second Reed's answer. However, when creating the enum, you must specify the values for each enum member so it makes a sort of bit field. For example:

    [Flags]
    public enum DaysOfWeek
    {
        Sunday = 1,
        Monday = 2,
        Tuesday = 4,
        Wednesday = 8,
        Thursday = 16,
        Friday = 32,
        Saturday = 64,
    
        None = 0,
        All = Weekdays | Weekend,
        Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday,
        Weekend = Sunday | Saturday,
        // etc.
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 17:18

    Reed Copsey is correct and I would add to the original post if I could, but I cant so I'll have to reply instead.

    Its dangerous to just use [Flags] on any old enum. I believe you have to explicitly change the enum values to powers of two when using flags, to avoid clashes in the values. See the guidelines for FlagsAttribute and Enum.

    0 讨论(0)
提交回复
热议问题