向枚举类型变量添加多个值



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

我引用了上面链接中的一段代码,其中显示了向枚举类型添加值。但这对我来说不起作用。预期输出代码:我得到了实际输出:

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

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

//预期产出:会议日期为周四、周五

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

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

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

此外,您应该使用Flags属性标记枚举,并且按照惯例使用零作为"未设置标志"。示例:

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

有关更多信息,请参阅C#编程指南。

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

您忘记使用FlagsAttribute了!

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

看看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属性。

[Flags]属性标记枚举。

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

相关内容

  • 没有找到相关文章

最新更新