Enum与int,string之间相互转换

 //枚举转字符串
            Console.WriteLine(Enum.GetName(typeof(Colors), 1));
            Console.WriteLine(Enum.GetName(typeof(Colors), Colors.Blue));
            Console.WriteLine(Enum.GetNames(typeof(Colors)).Length);

            //字符串转枚举
            object obj = (Colors)Enum.Parse(typeof(Colors),"Blue",false);

            //枚举转Int
            int red = (int)Colors.Red;
            int green = (int)Colors.Green;

            //Int转枚举
            Colors col = (Colors)3;
            Colors col2 = (Colors)Enum.ToObject(typeof(Colors), 2);

            //判断是否存在枚举成员
           bool isDef =  Enum.IsDefined(typeof(Colors),"Blue");
            //直接输出字符串枚举
           Console.WriteLine(Colors.Yellow.ToString());
            Console.ReadKey();

猜你喜欢

转载自blog.csdn.net/LUOCHENLONG/article/details/82896754