gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:59:16 25 4
gpt4 key购买 nike

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

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

请引用代码:**
//预期输出: session 日为周二、周四、周五

//实际输出: session 日为周五

//预期输出: session 日为周四、周五

//Actaul 输出: session 日是星期一**

     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# Programming Guide了解更多信息。

关于c# - 向枚举类型变量添加多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5858439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com