C# - Enum 使用方式

1.enum 指定型別

2.檢查要轉換的變數是否在範圍內,int 轉enum

3.enum 轉 int

4.列舉enum 所有的 value

5.列出enum 所有的 value

void Main()
{
	
	int testValue = 7;

	// 2.檢查要轉換的變數是否在Enum的範圍之內
	if (!Enum.IsDefined(typeof(DayOfWeekType), testValue))
	{
		"Error".Dump();
	}

	// 2.convert int to enum
	DayOfWeekType dayOfWeek = (DayOfWeekType)testValue;
	$"Convert int to enum:{dayOfWeek}".Dump();

	// 3.Convert enum to int
	int sunday = DayOfWeekType.Sunday.GetHashCode();
	$"Convert enum to int:{sunday}".Dump();

    // 4.列舉Enum所有的值
	int[] dayOfWeekValues = (int[])Enum.GetValues(typeof(DayOfWeekType));
	"列舉Enum所有的值:".Dump();
	foreach (var value in dayOfWeekValues)
	{
		$"Value:{value}".Dump();
	}

    // 5.列舉Enum所有的Names
	string[] dayOfWeekNames = Enum.GetNames(typeof(DayOfWeekType));
	"列舉Enum所有的Names:".Dump();
	foreach (var name in dayOfWeekNames)
	{
		$"Name:{name}".Dump();
	}

}

// 1.定義enum,可以在後面指定型別,預設是int
public enum DayOfWeekType : int
{
	/// <summary>
	/// 星期一
	/// </summary>
	Monday = 1,

	/// <summary>
	/// 星期二
	/// </summary>
	Tuesday = 2,

	/// <summary>
	/// 星期三
	/// </summary>
	Wednesday = 3,

	/// <summary>
	/// 星期四
	/// </summary>
	Thursday = 4,

	/// <summary>
	/// 星期五
	/// </summary>
	Friday = 5,

	/// <summary>
	/// 星期六
	/// </summary>
	Saturday = 6,

	/// <summary>
	/// 星期日
	/// </summary>
	Sunday = 7
}