平時咱們需要把Enum類型與int(或者string)類型進行相互轉換,利用下面的泛型編程,能夠處理全部狀況了。編程
- public static class EnumHelper2<T>
- {
- public static String Enum2String(T value)
- {
- return value.ToString();
- }
- public static T String2Enum(string value, bool ignoreCase)
- {
- return (T)Enum.Parse(typeof(T), value, ignoreCase);
- }
- public static int Enum2Int(T value)
- {
- return Convert.ToInt32(value);
- }
- public static T Int2Enum(int value)
- {
- if (Enum.IsDefined(typeof(T), value))
- return (T)Enum.ToObject(typeof(T), value);
- else
- throw new Exception(value + " is not defined");
- }
- }
- public static class EnumHelper
- {
- public static int ToInt32<T>(T value)
- {
- return Convert.ToInt32(value);
- }
- public static T FromInt32<T>(int value)
- {
- return (T)Enum.ToObject(typeof(T), value);
- }
- public static T Parse<T>(string value, bool ignoreCase)
- {
- if (Enum.IsDefined(typeof(T), value))
- return (T)Enum.Parse(typeof(T), value, ignoreCase);
- else
- throw new Exception(value + " is not defined");
- }
- public static T Parse<T>(int value)
- {
- if (Enum.IsDefined(typeof(T), value))
- return (T)Enum.ToObject(typeof(T), value);
- else
- throw new Exception(value + " is not defined");
- }
- }