1. 程式人生 > >C#列舉值與字串相互獲取

C#列舉值與字串相互獲取

namespace 列舉
{
    class Program
    {
        static void Main(string[] args)
        {
            //<Enum.GetNames(typeof(Week)).Length 獲取列舉的總個數
            //
            for (int i = 0; i < Enum.GetNames(typeof(Week)).Length; i++)
            {
                //用列舉只獲取字串
                Console.WriteLine($"{i}={Enum.GetName(typeof(Week), i)}");
                //輸出:
                /*
                0=星期天
                1=星期一
                .
                .
                .
                */
            }
            //用字串獲取列舉值
            Week week = (Week)Enum.Parse(typeof(Week), "星期天");
            Console.WriteLine((int)week);
            //輸出:
            /*
             0
             */
        }
        public enum Week
        {
            星期天 = 0,
            星期一 = 1,
            星期二 = 2,
            星期三 = 3,
            星期四 = 4,
            星期五 = 5,
            星期六 = 6
        }
    }
}