枚举遍历 public enum EMyType { [System.ComponentModel.Description("A类型")] TypeA = 1, [System.ComponentModel.Description("B类型")] TypeB = 1, [System.ComponentModel.Description("C类型")] TypeC = 2, } 接着遍历其枚举名的方法是 [csharp] view plain copy foreach (var name in Enum.GetNames(typeof(EMyType))) { Console.WriteLine(name); } 接着遍历其枚举名与枚举值的方法是 [csharp] view plain copy foreach (var value in Enum.GetValues(typeof(EMyType))) { Console.WriteLine(string.Format("{0}={1}", value.ToString(), Convert.ToInt32(value))); } 接着遍历其枚举名,枚举值与描述属性的字符串的方法是 [csharp] view plain copy foreach (var value in Enum.GetValues(typeof(EMyType))) { object[] objAttrs = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true); if (objAttrs != null && objAttrs.Length > 0) { DescriptionAttribute descAttr = objAttrs[0] as DescriptionAttribute; Console.WriteLine(string.Format("[{0}]", descAttr.Description)); } Console.WriteLine(string.Format("{0}={1}", value.ToString(), Convert.ToInt32(value))); }
枚举反射,根据枚举中的val或者data读取值和描述
举例实用:
1 Type t = Assembly.Load("XXX.SDK").GetType("XXX.SDK.Entities." + ObjType); 2 var dataList = new List<object>(); 3 foreach (var value in Enum.GetValues(t)) 4 { 5 6 object[] objAttrs = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true); 7 DescriptionAttribute descAttr = objAttrs[0] as DescriptionAttribute; 8 var date = new 9 { 10 Description = descAttr.Description, 11 Name = value.ToString(), 12 value = Convert.ToInt32(value) 13 }; 14 dataList.Add(date); 15 }
根据枚举的名字,读出枚举的描述,内容和值。
UserCardStatus userCardStatu = (UserCardStatus)Enum.Parse(typeof(UserCardStatus), result.user_card_status, true); string txt = GetEnumDescription(userCardStatu); public string GetEnumDescription(Enum enumValue) { string str = enumValue.ToString(); FieldInfo field = enumValue.GetType().GetField(str); object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (objs == null || objs.Length == 0) return str; DescriptionAttribute da = (DescriptionAttribute)objs[0]; return da.Description; }
根据枚举的单个内容,读出描述
时间: 2024-11-24 22:37:18