简体   繁体   中英

Adding multiple values to Enum Type variable

http://msdn.microsoft.com/en-us/library/cc138362.aspx

I refer a code from above link which is showing adding values to Enum Type. but its not working at my end. The code is expected output: I am getting actual output:

Please refer code: **
// Expected Output: Meeting days are Tuesday, Thursday, Friday

// Actual Output: Meeting days are Friday

// Expected Output: Meeting days are Thursday, Friday

// Actaul Output: Meeting days are Monday**

     class Program
{
    enum Days2
    {
        None = 1,
        Sunday = 2,
        Monday = 3,
        Tuesday = 4,
        Wednesday = 5,
        Thursday = 6,
        Friday = 7,
        Saturday = 8
    }



    static void Main(string[] args)
    {
        Days2 meetingDays = Days2.Tuesday | Days2.Thursday;

        // Initialize with two flags using bitwise OR.
        meetingDays = Days2.Tuesday | Days2.Thursday;

        // Set an additional flag using bitwise OR.
        meetingDays = meetingDays | Days2.Friday;


        Console.WriteLine("Meeting days are {0}", meetingDays);
        // Expected Output: Meeting days are Tuesday, Thursday, Friday
        **// Actual Output: Meeting days are  Friday**

        // Remove a flag using bitwise XOR.
        meetingDays = meetingDays ^ Days2.Tuesday;
        Console.WriteLine("Meeting days are {0}", meetingDays);

        // Expected Output: Meeting days are Thursday, Friday
        **// Actaul Output: Meeting days are Monday**

        Console.ReadLine();

    }
}

In order to be able to use bitwise operations to combine enum values, they need to have values that correspond to powers of two.

Additionally, you should mark the enum with the Flags attribute, and by convention use zero as "no flags set". Example:

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

See the C# Programming Guide for more info.

Add [Flags] attribute to your enum.

Look at the value of Days2.Tuesday | Days2.Thursday;Days2.Tuesday | Days2.Thursday; It should be 10. A bitwise AND is essentially an addition.

If you want several days, do them this way, binary style:

enum Days2
{
    None = 0,
    Sunday = 1,
    Monday = 2,
    Tuesday = 4,
    Wednesday = 8,
    Thursday = 16,
    Friday = 32,
    Saturday = 64    
}

Or use the Flags attribute as others stated.

Mark the enum with [Flags] attribute.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM