平时我们须要把Enum类型与int(或者string)类型进行相互转换,利用下面的泛型编程,可以处理所有情况了。

 
  
  1. public static class EnumHelper2<T> 
  2.     public static String Enum2String(T value) 
  3.     { 
  4.         return value.ToString(); 
  5.     } 
  6.  
  7.     public static T String2Enum(string value, bool ignoreCase) 
  8.     { 
  9.         return (T)Enum.Parse(typeof(T), value, ignoreCase); 
  10.     } 
  11.  
  12.     public static int Enum2Int(T value) 
  13.     { 
  14.         return Convert.ToInt32(value); 
  15.     } 
  16.  
  17.     public static T Int2Enum(int value) 
  18.     { 
  19.         if (Enum.IsDefined(typeof(T), value)) 
  20.             return (T)Enum.ToObject(typeof(T), value); 
  21.         else 
  22.             throw new Exception(value + " is not defined"); 
  23.     } 
  24.  
  25. public static class EnumHelper 
  26.     public static int ToInt32<T>(T value) 
  27.     { 
  28.         return Convert.ToInt32(value); 
  29.     } 
  30.  
  31.     public static T FromInt32<T>(int value) 
  32.     { 
  33.         return (T)Enum.ToObject(typeof(T), value); 
  34.     } 
  35.  
  36.     public static T Parse<T>(string value, bool ignoreCase) 
  37.     { 
  38.         if (Enum.IsDefined(typeof(T), value)) 
  39.             return (T)Enum.Parse(typeof(T), value, ignoreCase); 
  40.         else 
  41.             throw new Exception(value + " is not defined"); 
  42.     } 
  43.  
  44.     public static T Parse<T>(int value) 
  45.     { 
  46.         if (Enum.IsDefined(typeof(T), value)) 
  47.             return (T)Enum.ToObject(typeof(T), value); 
  48.         else 
  49.             throw new Exception(value + " is not defined"); 
  50.     }