向Enum Type变量添加多个值

时间:2011-05-02 14:33:59

标签: c# enums

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

我引用上面链接中的代码,该代码显示向Enum Type添加值。 但它不适合我。 代码是预期的输出: 我得到实际输出:

请参考代码: **
//预期产出:会议日为周二,周四,周五

//实际输出:会议日为星期五

//预期输出:会议日是星期四,星期五

// Actaul输出:会议日是星期一**

     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();

    }
}

5 个答案:

答案 0 :(得分:10)

为了能够使用按位运算来组合枚举值,它们需要具有与2的幂相对应的值。

此外,您应该使用Flags属性标记枚举,并按惯例使用零作为“无标志设置”。例如:

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

有关详细信息,请参阅C# Programming Guide

答案 1 :(得分:2)

将[Flags]属性添加到枚举。

答案 2 :(得分:2)

答案 3 :(得分:2)

查看Days2.Tuesday | Days2.Thursday;的值应该是10.按位AND本质上是一个补充。

如果你想要几天,就这样做,二元风格:

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

或者像其他人所说的那样使用Flags属性。

答案 4 :(得分:1)

使用[Flags]属性标记枚举。

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