C# enum、int、string三种类型互相转换

enum、int、string三种类型之间的互转

#代码:

 1 public enum Sex
 2 { 
 3     Man=1,
 4     Woman=2
 5 }
 6 
 7 public static void enumConvert()
 8 {
 9     int sexNum = (int)Sex.Man;
10     Console.WriteLine("将枚举转换成整数:"+sexNum);//1
11 
12     string sexStr = Sex.Woman.ToString();
13     Console.WriteLine("将枚举转换成字符串:"+sexStr);//"Woman"
14 
15     Sex sexStrEnum = (Sex)Enum.Parse(typeof(Sex),"Man");
16     Console.WriteLine("将字符串转换成枚举:" + sexStrEnum.ToString());//"Man"
17 
18     Sex sexNumEnum = (Sex)1;
19     Console.WriteLine("将整数转换成枚举:"+sexNumEnum.ToString());//"Man"
20 
21     string numToStr = Enum.GetName(typeof(Sex),2);
22     Console.WriteLine("将整数转换成字符串:"+numToStr);//"Woman"
23 
24     int strToNum = (int)Enum.Parse(typeof(Sex), "Woman");
25     Console.WriteLine("将字符串转换成整数:" + strToNum);//2
26 }

 

#结果:

 

 

      willingtolove

***————————————————***

 

posted @ 2018-08-28 21:15  willingtolove  阅读(1772)  评论(0编辑  收藏  举报