enum的使用

csharp

浏览数:186

2019-1-7

AD:资源代下载服务


program.cs

class  Program  
 4 {  
 5     public   enum  Color  
 6    {  
 7       Red  =   0xff0000 ,  
 8       Orange  =   0xFFA500 ,  
 9       Yellow  =   0xFFFF00 ,  
10       Lime  =   0x00FF00 ,  
11       Cyan  =   0x00FFFF ,  
12       Blue  =   0x0000FF ,  
13       Purple  =   0x800080   
14    }  
15   
16     static   void  Main( string [] args)  
17    {  
18       Color color  =  Color.Blue;  
19        string  colorString  =   " Blue " ;  
20        int  colorValue  =   0x0000FF ;  
21   
22        // 枚举转字符串   
23        string  enumStringOne  =  color.ToString(); //效率低,不推荐  
24        string  enumStringTwo  =  Enum.GetName( typeof (Color), color);//推荐  
25   
26        // 枚举转值   
27        int  enumValueOne  =  color.GetHashCode();  
28        int  enumValueTwo  =  ( int )color;  
29        int  enumValueThree  =  Convert.ToInt32(color);  
30   
31        // 字符串转枚举   
32       Color enumOne  =  (Color)Enum.Parse( typeof (Color), colorString);  
33   
34        // 字符串转值   
35        int  enumValueFour  =  ( int )Enum.Parse( typeof (Color), colorString);  
36   
37        // 值转枚举   
38       Color enumTwo  =  (Color)colorValue;  
39       Color enumThree  =  (Color)Enum.ToObject( typeof (Color), colorValue);  
40   
41        // 值转字符串   
42        string  enumStringThree  =  Enum.GetName( typeof (Color), colorValue);  
43    }  
44 }