平时咱们需要把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");
- }
- }