枚举静态类
class Program { static void Main(string[] args) { var s = typeof(SendMsgResultCodes).GetIntsFromEnum(); var a =typeof(SendMsgResultCodes).GetTextsFromEnum(); var b = SendMsgResultCodes.IP限制.ToInt(); var c = SendMsgResultCodes.IP限制.ToInt().IntToStringBaseEnum(typeof(SendMsgResultCodes)); var d = "单个手机号请求发送成功".StringToIntBaseEnum(typeof(SendMsgResultCodes)); var f = "a".StringToIntBaseEnum(typeof(SendMsgResultCodes)); } } public enum SendMsgResultCodes { 多个手机号请求发送成功 = 00, IP限制 = 02, 单个手机号请求发送成功 = 03, 用户名错误 = 04, 密码错误 = 05, 编码错误 = 06, 发送时间有误 = 07, 参数错误 = 08, 手机号码有误 = 09, 扩展号码有误 = 10, 余额不足 = 11, 服务器内部异常 = -1, } public static class EnumExt { /// <summary> /// 获取枚举所有文字 /// typeof(SendMsgResultCodes).GetTextsFromEnum() /// </summary> /// <param name="t"></param> /// <returns></returns> public static List<string> GetTextsFromEnum(this Type t) { if (t.IsEnum) { string[] names = Enum.GetNames(t); return names.ToList(); } else { throw new InvalidCastException("非枚举类型不支持该方法"); } } /// <summary> /// 获取枚举所有Int值 /// typeof(SendMsgResultCodes).GetIntsFromEnum() /// </summary> /// <param name="e"></param> /// <returns></returns> public static List<int> GetIntsFromEnum(this Type t) { var texts = t.GetTextsFromEnum(); List<int> list = new List<int>(); foreach (var item in texts) { int c = (int)Enum.Parse(t, item); list.Add(c); } return list; } /// <summary> /// 将枚举转化为int型 /// SendMsgResultCodes.IP限制.ToInt() /// </summary> /// <param name="e"></param> /// <returns></returns> public static int ToInt(this Enum e) { return (int)System.Enum.Parse(e.GetType(), e.ToString()); } /// <summary> /// 字符串转化枚举中的int /// "单个手机号请求发送成功".StringToIntBaseEnum(typeof(SendMsgResultCodes)) /// </summary> /// <param name="s"></param> /// <param name="t"></param> /// <returns></returns> public static int StringToIntBaseEnum(this string s, Type t) { var listTexts = t.GetTextsFromEnum(); var listInts = t.GetIntsFromEnum(); int i = 0; if (!listTexts.Contains(s)) { throw new InvalidCastException(s + "不是枚举"+t+"里面的值!"); } foreach (var item in listTexts) { if (item.Equals(s)) { return listInts[i]; } i++; } return 0; } /// <summary> /// int转化为枚举中的字符串 /// </summary> /// <param name="s"></param> /// <param name="t"></param> /// <returns></returns> public static string IntToStringBaseEnum(this int s, Type t) { var listTexts = t.GetTextsFromEnum(); var listInts = t.GetIntsFromEnum(); int i = 0; if (!listInts.Contains(s)) { throw new InvalidCastException(s + "不是枚举" + t + "里面的值!"); } foreach (var item in listInts) { if (item == s) { return listTexts[i]; } i++; } return string.Empty; } }