开发者

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 开发者_StackOverflowto 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.


You forgot to use FlagsAttribute!

  • http://msdn.microsoft.com/es-es/library/system.flagsattribute(v=vs.80).aspx


Look at the value of 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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜