C# 中枚举的使用
枚举定义
枚举对应的值也可以直接写成10进制
[Flags]
public enum Days
{
None = 0b_0000_0000, // 0
Monday = 0b_0000_0001, // 1
Tuesday = 0b_0000_0010, // 2
Wednesday = 0b_0000_0100, // 4
Thursday = 0b_0000_1000, // 8
Friday = 0b_0001_0000, // 16
Saturday = 0b_0010_0000, // 32
Sunday = 0b_0100_0000, // 64
Weekend = Saturday | Sunday
}
使用方式
- 赋值
Days meetingDays = Days.Monday | Days.Wednesday | Days.Friday;
- 取值
if ((meetingDays & Days.Monday)==Days.Monday) { Console.Write("is " +Days.Monday.ToString()); }
完整代码演示
public enum Days
{
None = 0b_0000_0000, // 0
Monday = 0b_0000_0001, // 1
Tuesday = 0b_0000_0010, // 2
Wednesday = 0b_0000_0100, // 4
Thursday = 0b_0000_1000, // 8
Friday = 0b_0001_0000, // 16
Saturday = 0b_0010_0000, // 32
Sunday = 0b_0100_0000, // 64
Weekend = Saturday | Sunday
}
public class FlagsEnumExample
{
public static void Main()
{
Days meetingDays = Days.Monday | Days.Wednesday | Days.Friday;
Console.WriteLine(meetingDays);
if ((meetingDays & Days.Monday)==Days.Monday)
{
Console.Write("is " +Days.Monday.ToString());//输出:true
}
if ((meetingDays & Days.Tuesday) == Days.Tuesday)
{
Console.Write("is " +Days.Tuesday.ToString());//不会进此分支
}
}
}
参考资料
原创不易,转载请声明 bindot
https://www.cnblogs.com/bindot/