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
}

使用方式

  1. 赋值
    Days meetingDays = Days.Monday | Days.Wednesday | Days.Friday;
  2. 取值
    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());//不会进此分支
		}
	}
}

参考资料

枚举类型 C#

posted @ 2022-12-02 17:13  FengLu-1  阅读(71)  评论(0编辑  收藏  举报