[.net]enum轉int, int轉enum

  • 6979
  • 0
  • 2017-10-24

[.net]enum轉int, int轉enum

class Program
{
	static void Main(string[] args)
	{
		//enumType to int
		string enumString = "enumType1";
		myEnum em = (myEnum)Enum.Parse(typeof(myEnum), enumString, false);
		Console.WriteLine(enumString +"轉換變成:" + Convert.ToString((int)em));
		
		//int to enumType
		int enumInt = 2;

		foreach (myEnum val in Enum.GetValues(typeof(myEnum)))
		{
			if (enumInt == (int)val)
			{
				Console.WriteLine(enumInt.ToString() + "轉換變成:" + val.ToString());
				break;

			}

		}
		Console.WriteLine("Press enter to continue");
		Console.ReadLine();
	   

	}


	public enum myEnum
	{
		enumType1 = 1,
		enumType2 = 2,
		enumType3 = 3
	}
}

執行結果:

以上~方便enum型態與數字的轉換,做個筆記囉

ps.20171024 補充:定義enum的時候,如果沒有給每個型別一個數字,也可以純粹當成程式碼內的自定義參數,就不用每個參數都要在db設定一筆資料,例子如下:

public enum TimerType
{
	PortTimer,
	PortOneDayTimer,
	SportWSTimer
}