转载:https://www.cnblogs.com/eliauk-L/p/16185682.html
1.定义枚举类型
public enum Test { 男 = 0, 女 = 1 }
public enum Test { 男, 女 }
2.获取枚举值ublic void EnumsAction()
public void EnumsAction() { var s = Test.男;//男 var s2 = (int)Test.男;//0 var a = Test.男.ToString();//"男" var r = (Test)1;//女 var x = (Test)Enum.Parse(typeof(Test), "男");//男 var x2 = Enum.Parse(typeof(Test), "男");//男 var x3 = Enum.GetName(typeof(Test), 0);//"男" foreach (var item in Enum.GetValues(typeof(Test))) { var v = item;//男[女] var v2 = (int)item;//0[1] var t = item.GetType();//{Name = "Test" FullName = "BaseControl.Enum.Test"} var g = item.ToString();//"男"["女"] } }
3.Enum Helper的使用
public static class EnumHelper { /// <summary> /// 根据枚举的值获取枚举名称 /// </summary> /// <typeparam name="T">枚举类型</typeparam> /// <param name="status">枚举的值</param> /// <returns></returns> public static string GetEnumName<T>(this int status) { return Enum.GetName(typeof(T), status); } /// <summary> /// 获取枚举名称集合 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static string[] GetNamesArr<T>() { return Enum.GetNames(typeof(T)); } /// <summary> /// 将枚举转换成字典集合 /// </summary> /// <typeparam name="T">枚举类型</typeparam> /// <returns></returns> public static Dictionary<string, int> getEnumDic<T>() { Dictionary<string, int> resultList = new Dictionary<string, int>(); Type type = typeof(T); var strList = GetNamesArr<T>().ToList(); foreach (string key in strList) { string val = Enum.Format(type, Enum.Parse(type, key), "d"); resultList.Add(key, int.Parse(val)); } return resultList; } /// <summary> /// 将枚举转换成字典 /// </summary> /// <typeparam name="TEnum"></typeparam> /// <returns></returns> public static Dictionary<string, int> GetDic<TEnum>() { Dictionary<string, int> dic = new Dictionary<string, int>(); Type t = typeof(TEnum); var arr = Enum.GetValues(t); foreach (var item in arr) { dic.Add(item.ToString(), (int)item); } return dic; } ///获取description信息 public static string GetDescription(Enum value) { if (value == null) { throw new ArgumentException("value"); } string description = value.ToString(); var fieldInfo = value.GetType().GetField(description); var attributes = (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false); if (attributes != null && attributes.Length > 0) { description = attributes[0].Description; } return description; } public static string GetEnumDescription2(Enum enumValue) { var field = enumValue.GetType().GetField(enumValue.ToString()); var objs = field.GetCustomAttribute(typeof(DescriptionAttribute)); var descriptionAttribute = (DescriptionAttribute)objs; return descriptionAttribute.Description; } }
标签:Enum,c#,enum,Test,枚举,typeof,var,public From: https://www.cnblogs.com/fangxinliu/p/16824332.html